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 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_failed">Delete failed</string>
<string name="delete">Delete</string>
<string name="edit">Edit</string>
<string name="are_you_sure">Are you sure?</string>
<string name="confirm">Confirm</string>
<string name="ok">OK</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.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 delete(int id) {
boolean result = true;
try {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
result = sqLiteDatabase.delete(contactTable, idColumn + " = ?", new String[]{ String.valueOf(id) }) > 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.DialogInterface;
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.AlertDialog;
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 android.widget.Toast;
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(final MenuItem item) {
if (item.getItemId() == R.id.deleteContactMenu) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.confirm);
builder.setMessage(R.string.are_you_sure);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
AdapterView.AdapterContextMenuInfo adapterContextMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
TextView textViewId = adapterContextMenuInfo.targetView.findViewById(R.id.textViewId);
int id = Integer.parseInt(textViewId.getText().toString());
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
if (databaseHelper.delete(id)) {
loadData();
} else {
Toast.makeText(getApplicationContext(), getText(R.string.delete_failed), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
}
return super.onContextItemSelected(item);
}
}
Structure of Project
Run App
Load Main Activity and Open Delete Menu
Display Confirm Dialog
Press OK Button Delete Data