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>
<string name="update_failed">Update failed</string>
<string name="delete">Delete</string>
<string name="edit">Edit</string>
</resources>
Create Context Menu
Create menu folder in res folder. Create crud_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/editContactMenu"
android:title="@string/edit" />
<item
android:id="@+id/deleteContactMenu"
android:title="@string/delete" />
</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.Cursor;
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 Contact find(int id) {
Contact contact = null;
try {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from " + contactTable + " where " + idColumn + " = ?", new String[] { String.valueOf(id) });
if (cursor.moveToFirst()) {
contact = new Contact();
do {
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhone(cursor.getString(2));
contact.setAddress(cursor.getString(3));
contact.setEmail(cursor.getString(4));
contact.setDescription(cursor.getString(5));
} while (cursor.moveToNext());
}
} catch (Exception e) {
contact = null;
}
return contact;
}
public boolean update(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.update(contactTable, contentValues, idColumn + " = ?", new String[]{ String.valueOf(contact.getId()) }) > 0;
} catch (Exception e) {
result = false;
}
return result;
}
}
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">
<ListView
android:id="@+id/listViewContact"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</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.demo.adapters.ContactListAdapter;
import android.demo.database.DatabaseHelper;
import android.demo.entities.Contact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listViewContact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
loadData();
}
private void initView() {
listViewContact = findViewById(R.id.listViewContact);
registerForContextMenu(listViewContact);
}
private void loadData() {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
List<Contact> contacts = databaseHelper.findAll();
if (contacts != null) {
listViewContact.setAdapter(new ContactListAdapter(getApplicationContext(), contacts));
}
}
@Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.crud_menu, contextMenu);
super.onCreateContextMenu(contextMenu, view, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.editContactMenu) {
AdapterView.AdapterContextMenuInfo adapterContextMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
TextView textViewId = adapterContextMenuInfo.targetView.findViewById(R.id.textViewId);
int id = Integer.parseInt(textViewId.getText().toString());
Intent intent = new Intent(MainActivity.this, EditContactActivity.class);
intent.putExtra("id", id);
startActivity(intent);
}
return super.onContextItemSelected(item);
}
}
EditContactActivity Layout
Create new activity named EditContactActivity.java. Open res\layout\activity_edit_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>
EditContactActivity Class
Add code to EditContactActivity.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 EditContactActivity 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;
private Contact contact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_contact);
initView();
loadData();
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 loadData() {
Intent intent = getIntent();
int id = intent.getIntExtra("id", 0);
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
contact = databaseHelper.find(id);
editTextName.setText(contact.getName());
editTextPhone.setText(contact.getPhone());
editTextEmail.setText(contact.getEmail());
editTextAddress.setText(contact.getAddress());
editTextDescription.setText(contact.getDescription());
}
private void buttonSave_onClick(View view) {
validator.validate();
}
private void buttonCancel_onClick(View view) {
Intent intent = new Intent(EditContactActivity.this, MainActivity.class);
startActivity(intent);
}
@Override
public void onValidationSucceeded() {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
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.update(contact)) {
Intent intent = new Intent(EditContactActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), getText(R.string.update_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();
}
}
}
}
Structure of Project
Run App
Load Main Activity and Open Edit Menu
Display Account Information
Press Save Button Update Data