Create Project
Create new project in Android Studio with steps as below:
Step 1: Input Project Name and Select Project Location
Step 2: Select SDK for Android App
Step 3: Select Default Activity for App
Step 4: Finish create project
Add Library as Dependency
Open build.gradle file in Gradle Scripts and add new library as below:
implementation 'com.mobsandgeeks:android-saripaar:2.0.3'
Add Strings
Open res\values\strings.xml file and add new string as below:
<resources>
<string name="app_name">Learn Android with Real Apps</string>
<string name="add_contact">Add Contact</string>
<string name="id">Id</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="address">Address</string>
<string name="email">Email</string>
<string name="description">Description</string>
<string name="save">Save</string>
<string name="cancel">Cancel</string>
<string name="insert_failed">Insert failed</string>
</resources>
Create Option Menu
Create menu folder in res folder. Create contact_menu.xml file contains menus as below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/addContactMenu"
android:title="@string/add_contact" />
</menu>
Create Entities
Create new package named entities. In this package, create new java class named Contact.java as below:
package android.demo.entities;
import java.io.Serializable;
public class Contact implements Serializable {
private int id;
private String name;
private String phone;
private String address;
private String email;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
Create DatabaseHelper
Create new package named database. In this package, create new java class named DatabaseHelper.java as below:
package android.demo.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.demo.entities.Contact;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String dbName = "ContactDB";
private static int dbVersion = 1;
private static String contactTable = "contact";
private static String idColumn = "id";
private static String nameColumn = "name";
private static String phoneColumn = "phone";
private static String addressColumn = "address";
private static String emailColumn = "email";
private static String descriptionColumn = "description";
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + contactTable + "(" +
idColumn + " integer primary key autoincrement, " +
nameColumn + " tex, " +
phoneColumn + " text, " +
addressColumn + " text, " +
emailColumn + " text, " +
descriptionColumn + " text " +
")"
);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists " + contactTable);
onCreate(sqLiteDatabase);
}
public boolean create(Contact contact) {
boolean result = true;
try {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(nameColumn, contact.getName());
contentValues.put(phoneColumn, contact.getPhone());
contentValues.put(addressColumn, contact.getAddress());
contentValues.put(emailColumn, contact.getEmail());
contentValues.put(descriptionColumn, contact.getDescription());
result = sqLiteDatabase.insert(contactTable, null, contentValues) > 0;
} catch (Exception e) {
result = false;
}
return result;
}
}
AddContactActivity Layout
Create new activity named AddContactActivity.java. Open res\layout\activity_add_contact.xml file and create layout as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AddContactActivity">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/name"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/phone"
android:inputType="phone" />
<EditText
android:id="@+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/address"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/editTextDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/description"
android:inputType="textMultiLine" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/save" />
<Button
android:id="@+id/buttonCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/cancel" />
</LinearLayout>
</LinearLayout>
AddContactActivity Class
Add code to AddContactActivity.java in android.demo.learnandroidwithrealapps package as below:
package android.demo.learnandroidwithrealapps;
import android.content.Intent;
import android.demo.database.DatabaseHelper;
import android.demo.entities.Contact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Pattern;
import java.util.List;
public class AddContactActivity extends AppCompatActivity implements Validator.ValidationListener {
@NotEmpty
private EditText editTextName;
@NotEmpty
@Pattern(regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$")
private EditText editTextPhone;
@NotEmpty
@Email
private EditText editTextEmail;
private EditText editTextAddress;
private EditText editTextDescription;
private Button buttonSave, buttonCancel;
private Validator validator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
initView();
validator = new Validator(this);
validator.setValidationListener(this);
}
private void initView() {
editTextName = findViewById(R.id.editTextName);
editTextPhone = findViewById(R.id.editTextPhone);
editTextEmail = findViewById(R.id.editTextEmail);
editTextAddress = findViewById(R.id.editTextAddress);
editTextDescription = findViewById(R.id.editTextDescription);
buttonSave = findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonSave_onClick(view);
}
});
buttonCancel = findViewById(R.id.buttonCancel);
buttonCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonCancel_onClick(view);
}
});
}
private void buttonSave_onClick(View view) {
validator.validate();
}
private void buttonCancel_onClick(View view) {
Intent intent = new Intent(AddContactActivity.this, MainActivity.class);
startActivity(intent);
}
@Override
public void onValidationSucceeded() {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
Contact contact = new Contact();
contact.setName(editTextName.getText().toString());
contact.setPhone(editTextPhone.getText().toString());
contact.setEmail(editTextEmail.getText().toString());
contact.setAddress(editTextAddress.getText().toString());
contact.setDescription(editTextDescription.getText().toString());
if(databaseHelper.create(contact)) {
Intent intent = new Intent(AddContactActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), getText(R.string.insert_failed), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}
}
Main Activity Layout
Open res\layout\activity_main.xml file and create layout as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
</LinearLayout>
Main Activity Class
Add code to MainActivity.java in android.demo.learnandroidwithrealapps package as below:
package android.demo.learnandroidwithrealapps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contact_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.addContactMenu) {
Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Structure of Project
Run App
Load Main Activity
Open Add Contact Menu
Test with Invalid Data
Test with Valid Data