How to create Android Contact Book App : Part 2 : Creating SQLite Database

As you seen in previous part, how we have created Interface for Contact Book App. So lets continue with next part.

Now we have the user interface to see Contacts and Input the Contact details. But where to store contact data. There is several ways of storing data. i.e. Text file, SQL database on web and accessing data through web services, SQLite etc.

In this app we are going to use SQLite database. The reason behind using SQLite database is, Android has native support for it, it data will store locally on user device.

Table of content


  1. Defining Table Structure
  2. Creating Contact Class
  3. Creating SQLite Database Handler Class to Handle Database
  4. Test Before Use
  5. Download Source

1. Defining Table Structure

Before we start implement database handler class we have to define table structure of the database. That is Columns of the table and it type as well as key. See the structure below.

Table Structure

2. Creating Contact Class

Create the Contact object class, for this create a new class file and name it Contact. This object will hold all the data of the single Contact.
So let’s create class for Contact and define all the getter and setter methods.

3. Creating SQLite Database Handler Class to Handle Database

Now create the Database Handler class named “Contact Handler” under src folder and extend this class with SQLiteOpenHelper.

We will create Contact table inside the onCreate() method. This method calls after create the database.

If there will be any changes in database structure, the onUpgrade() method calls.

a. Adding contact

To add the contact details in to database, define the method named “addContactDetails” with the Contact object argument and return type will be the boolean. so after inserting contact into database the method will return true or false boolean to confirm the data is stored in table or not.

b. Reading Contacts

Now let’s write the method named ” readAllContacts ” to reading contacts with return type List.

c. Updating Contact

Define the method to update the contact.

d. Deleting Contact

And method for delete single Contact

Complete ContactHandler Class

4. Test Before use.

Before using Contact Handler Class, let’s take a simple test.

Add few contacts from main file.

And read all inserted contact using LogCat.

Run app on Emulator and see the result into LogCat.

LogCat

1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *