http://icyarena.com
http://icyarena.com
Android SQLite database Tutorial (create, insert, update, delete, filter)
  Posted by : Color Picker     Date : 01 May       Leave a comment
Hey !
Today i will discuss about android SQLite database with complete example (create, insert, update, delete, filter)
in this tutorial we are going to make an app that shows you a list of some contacts. when you click on any list item, a new screen will come with details of selected contacts.A search filter helps you to find a specific contact.To edit, insert and delete  an item this app will also contain some buttons.

Let's start....
SQLite:
Android provides several ways to store user and app data. SQLite is one way of storing user data. SQLite is a very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.
If you have some basic about sql command than it will be easy for you to understand Android SQLite database.However this tutorial is for everyone who wants to develop android app using SQLite.

As exapmle, the name of our database is "ContactsDB", it has one table called "contacts" with five columns (_id, name, number, email, address)
contacts Table Structure is like below
To create our database simple sql command will be
CREATE TABLE contacts (_id INTEGER PRIMARY KEY autoincrement,name, number, email, address, UNIQUE(number))
To delete contacts table sql command will be
DROP TABLE IF EXISTS contacts
To update data
UPDATE contacts SET name='', number='', email='y@y.co', address=''  WHERE id=ID_NO
To delete a data
DELETE FROM contacts WHERE _id=ID_NO
To insert data
INSERT INTO contacts (name, number, email, address) VALUES('Color Picker','+85601487','info@icyarena.com','US')
Let's make an app with these basics.
Create Project
Open your Android Studio and Create the new Android project with the name com.android.contactlist and an activity called MainActivity.
Create Database Adapter
Create the DbAdapter class. This class is responsible for creating the database.in ths class we will define some static variables.For example:
public static int dbversion =1;
public static String dbname = "ContactsDB",
public static String dbTable = "contacts";
Note:If you want to delete old database, just increase database version
Than we will use Android DatabaseHelper class to create our database. DbAdapter class looks like
public class DbAdapter {
    //define static variable
    public static int dbversion =1;
    public static String dbname = "ContactsDB";
    public static String dbTable = "contacts";

    //create db
    private static class DatabaseHelper extends SQLiteOpenHelper {
        public DatabaseHelper(Context context) {
            super(context,dbname,null, dbversion);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE "+dbTable+" (_id INTEGER PRIMARY KEY autoincrement,name, number, email, address, UNIQUE(number))");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+dbTable);
            onCreate(db);
        }
    }
    //establsh connection with SQLiteDataBase  
    //insert data
    //edit data
    //delete data
    //fetch data
    //fetch data by filter
}
To establish connection with SQLiteDataBase we need to have some static variables and than define database open() function.
private final Context c;
private DatabaseHelper dbHelper;
private SQLiteDatabase sqlDb;

public DbAdapter(Context context) {
    this.c = context;
}
public DbAdapter open() throws SQLException {
    dbHelper = new DatabaseHelper(c);
    sqlDb = dbHelper.getWritableDatabase();
    return this;
}
So now DbAdapter class s like
public class DbAdapter {
    //define static variable
    public static int dbversion =1;
    public static String dbname = "ContactsDB";
    public static String dbTable = "contacts";
    
    private static class DatabaseHelper extends SQLiteOpenHelper {
        public DatabaseHelper(Context context) {
            super(context,dbname,null, dbversion);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE "+dbTable+" (_id INTEGER PRIMARY KEY autoincrement,name, number, email, address, UNIQUE(number))");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+dbTable);
            onCreate(db);
        }
    }

    //establsh connection with SQLiteDataBase
    private final Context c;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase sqlDb;

	public DbAdapter(Context context) {
	    this.c = context;
	}
	public DbAdapter open() throws SQLException {
	    dbHelper = new DatabaseHelper(c);
	    sqlDb = dbHelper.getWritableDatabase();
	    return this;
	}
    
    //insert data
    //edit data
    //delete data
    //fetch data
    //fetch data by filter
}
insert data
Now we need to insert some datas to make our app working. Here is a function to insert data to database
public void insert(String text2,String text3,String text4,String text5) {
    sqlDb.execSQL("INSERT INTO contacts (name,number,email,address) VALUES('"+text2+"','"+text3+"','"+text4+"','"+text5+"')");
}
Though this ok but our Databse has one unique feld so we must compare if unique field i.e "number" already conatains a contact number that we want to insert.
public boolean isExist(String num){
    String query = "SELECT number FROM contacts WHERE number='"+num+"' LIMIT 1";
    Cursor row = sqlDb.rawQuery(query, null);
    return row.moveToFirst();
}
so finally it will be
public void insert(String text2,String text3,String text4,String text5) {
    if(!isExist(text3)) {
    	sqlDb.execSQL("INSERT INTO contacts (name,number,email,address) VALUES('"+text2+"','"+text3+"','"+text4+"','"+text5+"')");
	}
}
public boolean isExist(String num){
    String query = "SELECT number FROM contacts WHERE number='"+num+"' LIMIT 1";
    Cursor row = sqlDb.rawQuery(query, null);
    return row.moveToFirst();
}
Edit data
public void update(int id, String text2, String text3, String text4, String text5) {
    sqlDb.execSQL("UPDATE "+dbTable+" SET name='"+text2+"', number='"+text3+"', email='"+text4+"', address='"+text5+"',   WHERE _id=" + id);
}
delete data
To delete data we need only _id value.
public void delete(int id) {
    sqlDb.execSQL("DELETE FROM "+dbTable+" WHERE _id="+id);
}
fetch data
To fetch all data we will use Android Cursor class.
public Cursor fetchAllData() {
    String query = "SELECT * FROM "+dbTable;
    Cursor row = sqlDb.rawQuery(query, null);
    if (row != null) {
        row.moveToFirst();
    }
    return row;
}
fetch data by filter
If we want to add search function then we need to filter data.Here we will define a function that takes two argument, one is inputText and another is filtercolumn i.e data will be fetched by filtering that column.
public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
    Cursor row = null;
    String query = "SELECT * FROM "+dbTable;
    if (inputText == null  ||  inputText.length () == 0)  {
        row = sqlDb.rawQuery(query, null);
    }else {
        query = "SELECT * FROM "+dbTable+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
        row = sqlDb.rawQuery(query, null);
    }
    if (row != null) {
        row.moveToFirst();
    }
    return row;
}
complete DbAdapter class (DbAdapter.java) looks
package com.android.contactlist;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DbAdapter {

    //define static variable
    public static int dbversion =1;
    public static String dbname = "ContactsDB";
    public static String dbTable = "contacts";
    
    private static class DatabaseHelper extends SQLiteOpenHelper {
        public DatabaseHelper(Context context) {
            super(context,dbname,null, dbversion);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE "+dbTable+" (_id INTEGER PRIMARY KEY autoincrement,name, number, email, address, UNIQUE(number))");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+dbTable);
            onCreate(db);
        }
    }

    //establsh connection with SQLiteDataBase
    private final Context c;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase sqlDb;

	public DbAdapter(Context context) {
	    this.c = context;
	}
	public DbAdapter open() throws SQLException {
	    dbHelper = new DatabaseHelper(c);
	    sqlDb = dbHelper.getWritableDatabase();
	    return this;
	}
    
    //insert data
    public void insert(String text2,String text3,String text4,String text5) {
	    if(!isExist(text3)) {
	    	sqlDb.execSQL("INSERT INTO contacts (name,number,email,address) VALUES('"+text2+"','"+text3+"','"+text4+"','"+text5+"')");
		}
	}
	//check entry already in database or not
	public boolean isExist(String num){
	    String query = "SELECT number FROM contacts WHERE number='"+num+"' LIMIT 1";
	    Cursor row = sqlDb.rawQuery(query, null);
	    return row.moveToFirst();
	}

    //edit data
    public void update(int id, String text2, String text3, String text4, String text5) {
	    sqlDb.execSQL("UPDATE "+dbTable+" SET name='"+text2+"', number='"+text3+"', email='"+text4+"', address='"+text5+"',   WHERE _id=" + id);
	}

    //delete data
    public void delete(int id) {
	    sqlDb.execSQL("DELETE FROM "+dbTable+" WHERE _id="+id);
	}

    //fetch data
    public Cursor fetchAllData() {
        String query = "SELECT * FROM "+dbTable;
        Cursor row = sqlDb.rawQuery(query, null);
        if (row != null) {
            row.moveToFirst();
        }
        return row;
    }

    //fetch data by filter
    public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
        Cursor row = null;
        String query = "SELECT * FROM "+dbTable;
        if (inputText == null  ||  inputText.length () == 0)  {
            row = sqlDb.rawQuery(query, null);
        }else {
            query = "SELECT * FROM "+dbTable+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
            row = sqlDb.rawQuery(query, null);
        }
        if (row != null) {
            row.moveToFirst();
        }
        return row;
    }
}
Works with MainActivity class
Now it is time to work with MainActivity class that will call this DbAdapter class and use all sql operations to make our app live.
Initially MainActivity class looks like
public class MainActivity extends AppCompatActivity {

    //calling variables
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

 		/* our jobs will be */
 		//calling DbAdapter
 		//initially insert some data
 		//display data
 		//onClick function
 		//dispay data by filter

    }
}
calling variables
DbAdapter db;
SimpleCursorAdapter adapter;
calling DbAdapter
db = new DbAdapter(this);
db.open();
initially insert some data
db.insert("Color Picker","+80885654","info@icyarena.com","US");
db.insert("Mike Helen","+80883437","halen@icyarena.com","UK");
db.insert("Robart Pink","+80881234","robart@icyarena.com","AUS");
display data
to display data activity_main.xml file must contain ListView object and another xml file for list styling.in my case it is liststyle.xml which contains two TextView object for showing name and number.We will use android SimpleCursorAdapter class for simplicity.
ListView lv = (ListView) findViewById(R.id.listView1);
int layoutstyle=R.layout.liststyle;
int[] xml_id = new int[] {
        R.id.txtname,
        R.id.txtnumber
};
String[] column = new String[] {
        "name",
        "number"
};
Cursor row = db.fetchAllData();
adapter = new SimpleCursorAdapter(this, layoutstyle,row,column, xml_id, 0);
lv.setAdapter(adapter);
onClick function
Here, only "_id" value of contact number are displayed as Toast message.Later we will extend this function to go to second screen where details of an item will be shown.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
        Cursor cursor = (Cursor) adapterview.getItemAtPosition(position);
        String ID = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
        Toast.makeText(getApplicationContext(),ID, Toast.LENGTH_SHORT).show();
    }
});
Dispay data by filtering "name" field
For filtering data activity_main.xml file must contain a search field.
EditText et = (EditText) findViewById(R.id.myFilter);
et.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        adapter.getFilter().filter(s.toString());
    }
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        return db.fetchdatabyfilter(constraint.toString(),"name");
    }
});
finaly the MainActivity looks like
package com.android.contactlist;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

    //calling variables
    DbAdapter db;
	SimpleCursorAdapter adapter;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 		
 		//calling DbAdapter
 		db = new DbAdapter(this);
		db.open();
 		//initially insert some data
 		db.insert("Color Picker","+80885654","info@icyarena.com","US");
		db.insert("Mike Helen","+80883437","halen@icyarena.com","UK");
		db.insert("Robart Pink","+80881234","robart@icyarena.com","AUS");
 		//display data
 		ListView lv = (ListView) findViewById(R.id.listView1);
		int layoutstyle=R.layout.liststyle;
		int[] xml_id = new int[] {
		        R.id.txtname,
		        R.id.txtnumber
		};
		String[] column = new String[] {
		        "name",
		        "number"
		};
		Cursor row = db.fetchAllData();
		adapter = new SimpleCursorAdapter(this, layoutstyle,row,column, xml_id, 0);
		lv.setAdapter(adapter);
 		//onClick function
 		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		    @Override
		    public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
		        Cursor cursor = (Cursor) adapterview.getItemAtPosition(position);
		        String ID = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
		        Toast.makeText(getApplicationContext(),ID, Toast.LENGTH_SHORT).show();
		    }
		});
 		//dispay data by filter
 		EditText et = (EditText) findViewById(R.id.myFilter);
		et.addTextChangedListener(new TextWatcher() {
		    public void afterTextChanged(Editable s) {
		    }
		    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		    }
		    public void onTextChanged(CharSequence s, int start, int before, int count) {
		        adapter.getFilter().filter(s.toString());
		    }
		});
		adapter.setFilterQueryProvider(new FilterQueryProvider() {
		    public Cursor runQuery(CharSequence constraint) {
		        return db.fetchdatabyfilter(constraint.toString(),"name");
		    }
		});

    }

	//code for add button
	public void addContact(View v){
		//
	}
}
Designing xml Layout
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <EditText android:id="@+id/myFilter" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:ems="10"
        android:hint="Search.....">
    </EditText>
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/add"
        android:layout_below="@+id/myFilter" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add"
        android:id="@+id/add"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="addContact" />
</RelativeLayout>
liststyle.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/txtname" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:layout_marginBottom="10dip"
        android:id="@+id/txtnumber" />

</LinearLayout>
If you run this app you will see a contact list with search box.when you click on any item it will show contact ID.Now we will modify our app by adding some buttons for working with insert new contact, delete and update function that we already defined.
Let's define addContact() onClick function to insert a new cotact.when we click on this button a second screen will appear and then we can insert a new contact.Create a class called addNewContact also create an xml file called store_contact.xml to design the page. In MainActivity class add this function
//code for add button
public void addContact(View v){
	Intent addNewContact = new Intent(MainActivity.this, addNewContact.class);
    startActivity(addNewContact);
}
store_contact.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:hint="Name"
            android:ems="10"
            android:id="@+id/name"
            android:layout_gravity="center_horizontal" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:hint="Number"
            android:ems="10"
            android:id="@+id/number"
            android:layout_gravity="center_horizontal" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:hint="Email"
            android:ems="10"
            android:id="@+id/email"
            android:layout_gravity="center_horizontal" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine"
            android:ems="10"
            android:id="@+id/address"
            android:layout_gravity="center_horizontal"
            android:hint="Address" />


    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:id="@+id/save"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="Save" />

</RelativeLayout>
addNewContact Class
package com.android.contactlist;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class addNewContact extends AppCompatActivity {
    //calling variables
    DbAdapter db;
    SimpleCursorAdapter adapter;
    EditText etname,etnumber,etemail,etaddress;
    String name,number,email,address;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_contact);
        //calling DbAdapter
        db = new DbAdapter(this);
        db.open();
        //get data from text feld
        etname =(EditText)findViewById(R.id.name);
        etnumber =(EditText)findViewById(R.id.number);
        etemail =(EditText)findViewById(R.id.email);
        etaddress = (EditText)findViewById(R.id.address);
    }
    public void Save(View v){
        if(db.isExist(number)){
            Toast.makeText(getApplicationContext(),"already exist", Toast.LENGTH_SHORT).show();
        }else{
            name=etname.getText().toString();
            number=etnumber.getText().toString();
            email=etemail.getText().toString();
            address=etaddress.getText().toString();
            db.insert(name,number,email,address);
            Toast.makeText(getApplicationContext(),"Contact added", Toast.LENGTH_SHORT).show();
        }

    }
}
If you run this app you will able to insert new contact
Edit or delete a contact number
Now we will add another function to edit or delete a existing contact. Previously, We wrote onClick method for contact list item, Now we will slightly edit this method to go to another screen to edit or to delete a contact number.
Go to MainActivity class and slghtly edit onClick method of contact list item.
//onClick function
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
        Cursor row = (Cursor) adapterview.getItemAtPosition(position);
        String _id = row.getString(row.getColumnIndexOrThrow("_id"));
        String name = row.getString(row.getColumnIndexOrThrow("name"));
        String number = row.getString(row.getColumnIndexOrThrow("number"));
        String email = row.getString(row.getColumnIndexOrThrow("email"));
        String address = row.getString(row.getColumnIndexOrThrow("address"));
        //go to detailsContact page
        Intent todetais = new Intent(MainActivity.this, DetailsContact.class);
        todetais.putExtra("ID",_id);
        todetais.putExtra("NAME", name);
        todetais.putExtra("NUMBER",number);
        todetais.putExtra("EMAIL",email);
        todetais.putExtra("ADDRESS",address);
        startActivity(todetais);
    }
});
DetailsContact class
package com.android.contactlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsContact extends AppCompatActivity {
    DbAdapter db;
    String id,name,number,email,address;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_contact);

        Intent intent = getIntent();
        id = intent.getStringExtra("ID");
        name = intent.getStringExtra("NAME");
        number = intent.getStringExtra("NUMBER");
        email = intent.getStringExtra("EMAIL");
        address = intent.getStringExtra("ADDRESS");
        ((TextView) findViewById(R.id.name)).setText(name);
        ((TextView) findViewById(R.id.number)).setText(number);
        ((TextView) findViewById(R.id.email)).setText(email);
        ((TextView) findViewById(R.id.address)).setText(address);
        //calling DbAdapter
        db = new DbAdapter(this);
        db.open();
    }
    public void Edit(View v){
        //go to EditContact page
        Intent edit = new Intent(DetailsContact.this, EditContact.class);
        edit.putExtra("ID",id);
        edit.putExtra("NAME", name);
        edit.putExtra("NUMBER",number);
        edit.putExtra("EMAIL",email);
        edit.putExtra("ADDRESS",address);
        startActivity(edit);
    }
    public void Delete(View v){
        db.delete(Integer.parseInt(id));
        Toast.makeText(getApplicationContext(),"deleted", Toast.LENGTH_SHORT).show();
    }
}
details_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Name"
            android:ems="10"
            android:layout_gravity="center_horizontal" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/name"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Number"
            android:ems="10"
            android:layout_gravity="center_horizontal" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:ems="10"
            android:id="@+id/number"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Email"
            android:ems="10"
            android:layout_gravity="center_horizontal" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:id="@+id/email"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text="Address"
            android:ems="10"
            android:layout_gravity="center_horizontal" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine"
            android:ems="10"
            android:id="@+id/address"
            android:layout_gravity="center_horizontal" />


    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit"
        android:onClick="Edit"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:onClick="Delete"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>
EditContact class
package com.android.contactlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsContact extends AppCompatActivity {
    DbAdapter db;
    String id,name,number,email,address;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details_contact);

        Intent intent = getIntent();
        id = intent.getStringExtra("ID");
        name = intent.getStringExtra("NAME");
        number = intent.getStringExtra("NUMBER");
        email = intent.getStringExtra("EMAIL");
        address = intent.getStringExtra("ADDRESS");
        ((TextView) findViewById(R.id.name)).setText(name);
        ((TextView) findViewById(R.id.number)).setText(number);
        ((TextView) findViewById(R.id.email)).setText(email);
        ((TextView) findViewById(R.id.address)).setText(address);
        //calling DbAdapter
        db = new DbAdapter(this);
        db.open();
    }
    public void Edit(View v){
        //go to EditContact page
        Intent edit = new Intent(DetailsContact.this, EditContact.class);
        edit.putExtra("ID",id);
        edit.putExtra("NAME", name);
        edit.putExtra("NUMBER",number);
        edit.putExtra("EMAIL",email);
        edit.putExtra("ADDRESS",address);
        startActivity(edit);
    }
    public void Delete(View v){
        db.delete(Integer.parseInt(id));
        Toast.makeText(getApplicationContext(),"deleted", Toast.LENGTH_SHORT).show();
    }
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.contactlist" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".addNewContact"
            android:label="Add new contact" />
        <activity
            android:name=".DetailsContact"
            android:label="Contact Details" />
        <activity
            android:name=".EditContact"
            android:label="Edit Contact" />
    </application>

</manifest>
If you don't understand anything please feel free to comment.You can download all Files if you need.At the end of this tutorial you will get Download Button

Complete Example Code

  • AndroidManifest.xml
  • activity_main.xml
  • details_contact.xml
  • liststyle.xml
  • store_contact.xml
  • File: app / manifests / AndroidManifest.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.android.contactlist" >
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <activity android:name=".MainActivity" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name=".addNewContact"
                android:label="Add new contact" />
            <activity
                android:name=".DetailsContact"
                android:label="Contact Details" />
            <activity
                android:name=".EditContact"
                android:label="Edit Contact" />
        </application>
    
    </manifest>
    File: app / res / layoutactivity_main.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <EditText android:id="@+id/myFilter" android:layout_width="match_parent"
            android:layout_height="wrap_content" android:ems="10"
            android:hint="Search.....">
        </EditText>
        <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/listView1"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_above="@+id/add"
            android:layout_below="@+id/myFilter" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add"
            android:id="@+id/add"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:onClick="addContact" />
    </RelativeLayout>
    File: app / res / layoutdetails_contact.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:text="Name"
                android:ems="10"
                android:layout_gravity="center_horizontal" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:ems="10"
                android:id="@+id/name"
                android:layout_gravity="center_horizontal" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:text="Number"
                android:ems="10"
                android:layout_gravity="center_horizontal" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:ems="10"
                android:id="@+id/number"
                android:layout_gravity="center_horizontal" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:text="Email"
                android:ems="10"
                android:layout_gravity="center_horizontal" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:ems="10"
                android:id="@+id/email"
                android:layout_gravity="center_horizontal" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:text="Address"
                android:ems="10"
                android:layout_gravity="center_horizontal" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:ems="10"
                android:id="@+id/address"
                android:layout_gravity="center_horizontal" />
    
    
        </LinearLayout>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Edit"
            android:onClick="Edit"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete"
            android:onClick="Delete"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    
    </RelativeLayout>
    File: app / res / layoutliststyle.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/txtname" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:layout_marginBottom="10dip"
            android:id="@+id/txtnumber" />
    
    </LinearLayout>
    File: app / res / layoutstore_contact.xmlText View
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:hint="Name"
                android:ems="10"
                android:id="@+id/name"
                android:layout_gravity="center_horizontal" />
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:hint="Number"
                android:ems="10"
                android:id="@+id/number"
                android:layout_gravity="center_horizontal" />
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:hint="Email"
                android:ems="10"
                android:id="@+id/email"
                android:layout_gravity="center_horizontal" />
    
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:ems="10"
                android:id="@+id/address"
                android:layout_gravity="center_horizontal"
                android:hint="Address" />
    
    
        </LinearLayout>
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/save"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:onClick="Save" />
    
    </RelativeLayout>
  • activity_main.xml
  • details_contact.xml
  • liststyle.xml
  • store_contact.xml
  • File: app / res / layoutactivity_main.xmlDesign View
    Screenshot: activity_main.xml
    File: app / res / layoutdetails_contact.xmlDesign View
    Screenshot: details_contact.xml
    File: app / res / layoutliststyle.xmlDesign View
    Screenshot: liststyle.xml
    File: app / res / layoutstore_contact.xmlDesign View
    Screenshot: store_contact.xml
  • DbAdapter.java
  • DetailsContact.java
  • EditContact.java
  • MainActivity.java
  • addNewContact.java
  • File: app / java / DbAdapter.javaText View
    package com.android.contactlist;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class DbAdapter {
    
        //define static variable
        public static int dbversion =6;
        public static String dbname = "ContactsDB";
        public static String dbTable = "contacts";
    
        private static class DatabaseHelper extends SQLiteOpenHelper {
            public DatabaseHelper(Context context) {
                super(context,dbname,null, dbversion);
            }
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("CREATE TABLE IF NOT EXISTS "+dbTable+" (_id INTEGER PRIMARY KEY autoincrement,name, number, email, address, UNIQUE(number))");
            }
    
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS "+dbTable);
                onCreate(db);
            }
        }
    
        //establsh connection with SQLiteDataBase
        private final Context c;
        private DatabaseHelper dbHelper;
        private SQLiteDatabase sqlDb;
    
        public DbAdapter(Context context) {
            this.c = context;
        }
        public DbAdapter open() throws SQLException {
            dbHelper = new DatabaseHelper(c);
            sqlDb = dbHelper.getWritableDatabase();
            return this;
        }
    
        //insert data
        public void insert(String text2,String text3,String text4,String text5) {
            if(!isExist(text3)) {
                sqlDb.execSQL("INSERT INTO contacts (name,number,email,address) VALUES('" + text2 + "','" + text3 + "','" + text4 + "','" + text5 + "')");
            }
        }
        //check entry already in database or not
        public boolean isExist(String num){
            String query = "SELECT number FROM contacts WHERE number='"+num+"' LIMIT 1";
            Cursor row = sqlDb.rawQuery(query, null);
            return row.moveToFirst();
        }
        //edit data
        public void update(int id,String text2,String text3,String text4,String text5) {
            sqlDb.execSQL("UPDATE "+dbTable+" SET name='"+text2+"', number='"+text3+"', email='"+text4+"', address='"+text5+"'   WHERE _id=" + id);
        }
    
        //delete data
        public void delete(int id) {
            sqlDb.execSQL("DELETE FROM "+dbTable+" WHERE _id="+id);
        }
    
        //fetch data
        public Cursor fetchAllData() {
            String query = "SELECT * FROM "+dbTable;
            Cursor row = sqlDb.rawQuery(query, null);
            if (row != null) {
                row.moveToFirst();
            }
            return row;
        }
    
        //fetch data by filter
        public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
            Cursor row = null;
            String query = "SELECT * FROM "+dbTable;
            if (inputText == null  ||  inputText.length () == 0)  {
                row = sqlDb.rawQuery(query, null);
            }else {
                query = "SELECT * FROM "+dbTable+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
                row = sqlDb.rawQuery(query, null);
            }
            if (row != null) {
                row.moveToFirst();
            }
            return row;
        }
    }
    File: app / java / DetailsContact.javaText View
    package com.android.contactlist;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class DetailsContact extends AppCompatActivity {
        DbAdapter db;
        String id,name,number,email,address;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.details_contact);
    
            Intent intent = getIntent();
            id = intent.getStringExtra("ID");
            name = intent.getStringExtra("NAME");
            number = intent.getStringExtra("NUMBER");
            email = intent.getStringExtra("EMAIL");
            address = intent.getStringExtra("ADDRESS");
            ((TextView) findViewById(R.id.name)).setText(name);
            ((TextView) findViewById(R.id.number)).setText(number);
            ((TextView) findViewById(R.id.email)).setText(email);
            ((TextView) findViewById(R.id.address)).setText(address);
            //calling DbAdapter
            db = new DbAdapter(this);
            db.open();
        }
        public void Edit(View v){
            //go to EditContact page
            Intent edit = new Intent(DetailsContact.this, EditContact.class);
            edit.putExtra("ID", id);
            edit.putExtra("NAME", name);
            edit.putExtra("NUMBER", number);
            edit.putExtra("EMAIL", email);
            edit.putExtra("ADDRESS",address);
            startActivity(edit);
        }
        public void Delete(View v){
            db.delete(Integer.parseInt(id));
            Toast.makeText(getApplicationContext(),"deleted", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onBackPressed() {
            finish();
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        }
    }
    File: app / java / EditContact.javaText View
    package com.android.contactlist;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class EditContact extends AppCompatActivity {
        DbAdapter db;
        String id,name,number,email,address;
        EditText etname,etnumber,etemail,etaddress;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.store_contact);
    
            Intent intent = getIntent();
            id = intent.getStringExtra("ID");
            name = intent.getStringExtra("NAME");
            number = intent.getStringExtra("NUMBER");
            email = intent.getStringExtra("EMAIL");
            address = intent.getStringExtra("ADDRESS");
            ((EditText) findViewById(R.id.name)).setText(name);
            ((EditText) findViewById(R.id.number)).setText(number);
            ((EditText) findViewById(R.id.email)).setText(email);
            ((EditText) findViewById(R.id.address)).setText(address);
            //calling DbAdapter
            db = new DbAdapter(this);
            db.open();
            //get data from text feld
            etname =(EditText)findViewById(R.id.name);
            etnumber =(EditText)findViewById(R.id.number);
            etemail =(EditText)findViewById(R.id.email);
            etaddress = (EditText)findViewById(R.id.address);
        }
        public void Save(View v){
            name=etname.getText().toString();
            number=etnumber.getText().toString();
            email=etemail.getText().toString();
            address=etaddress.getText().toString();
            db.update(Integer.parseInt(id),name, number, email, address);
            Toast.makeText(getApplicationContext(),"Update success", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onBackPressed() {
            finish();
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        }
    }
    File: app / java / MainActivity.javaText View
    package com.android.contactlist;
    
    import android.content.Intent;
    import android.database.Cursor;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.EditText;
    import android.widget.FilterQueryProvider;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.Toast;
    public class MainActivity extends AppCompatActivity {
    
        //calling variables
        DbAdapter db;
        SimpleCursorAdapter adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //calling DbAdapter
            db = new DbAdapter(this);
            db.open();
            //initially insert some data
            //db.insert("Color Picker", "+840885654", "info@icyarena.com", "US");
            //db.insert("Mike Helen", "+808853437", "halen@icyarena.com", "UK");
            //db.insert("Robart Pink", "+808851234", "robart@icyarena.com", "AUS");
            //display data
            ListView lv = (ListView) findViewById(R.id.listView1);
            int layoutstyle=R.layout.liststyle;
            int[] xml_id = new int[] {
                    R.id.txtname,
                    R.id.txtnumber
            };
            String[] column = new String[] {
                    "name",
                    "number"
            };
            Cursor row = db.fetchAllData();
            adapter = new SimpleCursorAdapter(this, layoutstyle,row,column, xml_id, 0);
            lv.setAdapter(adapter);
            //onClick function
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
                    Cursor row = (Cursor) adapterview.getItemAtPosition(position);
                    String _id = row.getString(row.getColumnIndexOrThrow("_id"));
                    String name = row.getString(row.getColumnIndexOrThrow("name"));
                    String number = row.getString(row.getColumnIndexOrThrow("number"));
                    String email = row.getString(row.getColumnIndexOrThrow("email"));
                    String address = row.getString(row.getColumnIndexOrThrow("address"));
                    //go to detailsContact page
                    Intent todetais = new Intent(MainActivity.this, DetailsContact.class);
                    todetais.putExtra("ID",_id);
                    todetais.putExtra("NAME", name);
                    todetais.putExtra("NUMBER",number);
                    todetais.putExtra("EMAIL",email);
                    todetais.putExtra("ADDRESS",address);
                    startActivity(todetais);
                }
            });
            //dispay data by filter
            EditText et = (EditText) findViewById(R.id.myFilter);
            et.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                }
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    adapter.getFilter().filter(s.toString());
                }
            });
            adapter.setFilterQueryProvider(new FilterQueryProvider() {
                public Cursor runQuery(CharSequence constraint) {
                    return db.fetchdatabyfilter(constraint.toString(),"name");
                }
            });
        }
        public void addContact(View v){
            Intent addNewContact = new Intent(MainActivity.this, addNewContact.class);
            startActivity(addNewContact);
    
    
        }
    
    }
    File: app / java / addNewContact.javaText View
    package com.android.contactlist;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.SimpleCursorAdapter;
    import android.widget.Toast;
    
    public class addNewContact extends AppCompatActivity {
        //calling variables
        DbAdapter db;
        EditText etname,etnumber,etemail,etaddress;
        String name,number,email,address;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.store_contact);
            //get data from text feld
            etname =(EditText)findViewById(R.id.name);
            etnumber =(EditText)findViewById(R.id.number);
            etemail =(EditText)findViewById(R.id.email);
            etaddress = (EditText)findViewById(R.id.address);
            //calling DbAdapter
            db = new DbAdapter(this);
            db.open();
        }
        public void Save(View v){
            if(db.isExist(number)){
                Toast.makeText(getApplicationContext(),"already exist", Toast.LENGTH_SHORT).show();
            }else{
                name=etname.getText().toString();
                number=etnumber.getText().toString();
                email=etemail.getText().toString();
                address=etaddress.getText().toString();
                db.insert(name,number,email,address);
                Toast.makeText(getApplicationContext(),"Contact added", Toast.LENGTH_SHORT).show();
            }
    
        }
        @Override
        public void onBackPressed() {
            finish();
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
        }
    }
    You may try :