Quantcast
Viewing latest article 9
Browse Latest Browse All 10

Android SQLite Database

In this post we will discuss how to store data in the android sqlite database. Android is using light weight open source sqlite database as one of the way to store data. Android provides two important classes SQLiteDatabase class to perform common database management tasks e.g. create, delete, execute SQL commands,etc and a helper class SQLiteOpenHelper to manage database creation and version management.


1. So first we will create a database helper class by extending SQLiteOpenHelper.
a. In the constructor we need to pass database name and version number. In this example i am creating the DatabaseHelper class as singleton class. So we can get instance of DatabaseHelper using static method getInstance.

  synchronized static DatabaseHelper getInstance(Context context) {
        if (singleton == null) {
            singleton = new DatabaseHelper(context.getApplicationContext());
        }
        return (singleton);
    }

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

b. For contact table column we are implementing BaseColumns interface. BaseColumns interface providers _id and _count column for us.

    public static final class ContactColumns implements BaseColumns {

        public static final String NAME = "name";

        public static final String PHONE_NUMBER = "phoneNumber";

        public static final String EMAIL = "email";

        public static final String ADDRESS = "address";
    }

c. override the onCreate method of SQLiteOpenHelper. onCreate method will be called when the database is created first time. In this method we will get the instance of SQLiteDatabase. We are using execSQL method of SQLiteDatabase for creating table. execSQL method doesn’t return anything so it should not be used for sql statement that return data.

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s = " (" +
                ContactColumns._ID + " INTEGER PRIMARY KEY, " +
                ContactColumns.NAME + " TEXT, " +
                ContactColumns.PHONE_NUMBER + " TEXT, " +
                ContactColumns.EMAIL + " TEXT, " +
                ContactColumns.ADDRESS + " TEXT" +
                ");";

        db.execSQL("CREATE TABLE " + TABLE_NAME + s);

    }

d. onUpgrade is the second method that we need to override. onUpgrade is called when database needs to be upgraded. Suppose address column was not there in version 1 of contact’s table.This column is added in version 2. In that case when you try to reinstall app with version 2 database onUpgrade method will be called. In onUpgrade method, we will check if old version is 1 , alter the table and add column address. for other versions just drop the table and create again.

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Logs that the database is being upgraded
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");

        // if (oldVersion == 1) {
        // try {
        // db.execSQL("alter table " + TABLE_NAME
        // + " add column " + "address" +
        // " TEXT;");
        // } catch (SQLException e) {
        // // Shouldn't be needed unless we're debugging and interrupt the
        // // process
        // Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " +
        // e);
        // }
        // } else {
        // // Drop older table if existed
        // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        //
        // // Create tables again
        // onCreate(db);
        // }
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        // Create tables again
        onCreate(db);

    }

}

2. create ContactData data only class. it will hold all contact information as single entity. We are making ContactData class Serializable because we can send ContactsData object from one activty to another or we can save state of activity with ContactsData object.

public class ContactsData implements Serializable{

    public int mId;
    public String mName;
    public String mPhoneNumber;
    public String mAddress;
    public String mEmail;

    public ContactsData(int id, String name, String phoneNumber) {
        this(id,name,phoneNumber,null,null);
    }
    
    public ContactsData(int id, String name, String phoneNumber,String address, String email) {
        mId = id;
        mName = name;
        mPhoneNumber = phoneNumber;
        mAddress = address;
        mEmail = email;
    }
    
    public ContactsData() {}


}

3. Now we will write methods for database read write operations.

 mDatabaseHelper = DatabaseHelper.getInstance(context);

Add new contact:

a. get writable databse.
b. store column name and value in ContentValues as key value pair
c. use insert method for inserting contacts data with arguments.
d. if values are empty, ContactColumns.NAME(nullColumnHack) column can be null.
e. insert method returns rowId of inserted row.

  // Adding new contact
    public void addContact(ContactsData contact){
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(ContactColumns.NAME, contact.mName); // Contact Name
        values.put(ContactColumns.PHONE_NUMBER, contact.mPhoneNumber); // Contact phone number
        values.put(ContactColumns.EMAIL, contact.mEmail); // Contact email
        values.put(ContactColumns.ADDRESS, contact.mAddress); // Contact address 
        // Inserting Row
        long rowId = db.insert(DatabaseHelper.TABLE_NAME, ContactColumns.NAME, values);
        db.close();
    }

Getting single contact:

a. get readable database.
b. we will use query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
c. query method will return resultset as cursor.

// Getting single contact
    public ContactsData getContact(int id) {
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();

              Cursor cursor = db.query(
                /* FROM */ DatabaseHelper.TABLE_NAME, 
                /* SELECT */ new String[] {ContactColumns._ID,ContactColumns.NAME, ContactColumns.PHONE_NUMBER}, 
                /* WHERE */ ContactColumns._ID + "=?",
                /* WHERE args */new String[] {String.valueOf(id)}, 
                /* GROUP BY */null, 
                /* HAVING */null, 
                /* ORDER BY */ ContactColumns.NAME+" DESC", 
                /* LIMIT */null);

        if (cursor != null)
            cursor.moveToFirst();
        ContactsData contact = new ContactsData(Integer.parseInt(
                cursor.getString(cursor.getColumnIndex(ContactColumns._ID))),
                cursor.getString(cursor.getColumnIndex(ContactColumns.NAME)),
                cursor.getString(cursor.getColumnIndex(ContactColumns.PHONE_NUMBER)));
        return contact;
    }

Get all contacts:

// Getting All Contacts
    public List getAllContacts() {
        List contactList = new ArrayList();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + DatabaseHelper.TABLE_NAME;

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        while (cursor.moveToNext()) {
            ContactsData contact = new ContactsData(Integer.parseInt(
                    cursor.getString(cursor.getColumnIndex(ContactColumns._ID))),
                    cursor.getString(cursor.getColumnIndex(ContactColumns.NAME)),
                    cursor.getString(cursor.getColumnIndex(ContactColumns.PHONE_NUMBER)));
            // Adding contact to list
            contactList.add(contact);

        }
        // return contact list
        return contactList;
    }

Update single contact:

 // Updating single contact
    public int updateContact(ContactsData contact) {
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(ContactColumns.NAME, contact.mName);
        values.put(ContactColumns.PHONE_NUMBER, contact.mPhoneNumber);

        // updating row
        return db.update(DatabaseHelper.TABLE_NAME, values, ContactColumns._ID + " = ?",
                new String[] {
                    String.valueOf(contact.mId)
                });
    }

Delete single contact:

    // Deleting single contact
    public void deleteContact(ContactsData contact) {
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        db.delete(DatabaseHelper.TABLE_NAME, ContactColumns._ID + " = ?",
                new String[] {
                    String.valueOf(contact.mId)
                });
        db.close();
    }

contact count:

 // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + DatabaseHelper.TABLE_NAME;
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

Incoming search terms:


Viewing latest article 9
Browse Latest Browse All 10

Trending Articles