Android Basics – Learn How to Update SQLite Database

In the last lecture you learnt how to create a database and also a table.

Let’s consider the following scenario. You roll out the Survey app and people start to use that. They take surveys and capture the data, which gets stored in the survey table. Everything looks good.

A month later you want to introduce a new column to the survey table. The column is meant to capture the “license” number as well.

So how to push this change ? For this scenario SQLiteOpenHelper onUpgrade() and onDowngrade() method comes in handy.

There can be two scenarios

1. A user downloads your app for the first time. In this case onCreate() method will be called.
2. A user updates the already installed app. In this case onUpgrade() or onDowngrade() method will be called.

So how does SQLite figure out if the database is out of date?

It’s based on the database version number. If you remember we defined a field in the helper class.

static final String DB_VERSION=”1″;

This version is passed to the constructor and if its greater than what was specified earlier then upgrade happens via onUpgrade() method.

Let’s look at the onUpgrade() method

This method takes three parameters.

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

So the logic you write is based on the oldVersion and newVersion parameters.

 

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

    if(oldVersion < 1){

        db.execSQL("CREATE TABLE "+SURVEY_TABLE+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        +SURVEY_TABLE_NAME_COLUMN+" TEXT, "
                        +SURVEY_TABLE_EMAIL_COLUMN+" TEXT, "
                        +SURVEY_TABLE_AGE_COLUMN+" INTEGER);"
        );

    }
    if(oldVersion < 2){
        //Perform Updates
        db.execSQL("ALTER TABLE "+SURVEY_TABLE+" ADD COLUMN "+SURVEY_TABLE_LICENSE_COLUMN+" TEXT");
    }
}

This code is available in Github here.

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

One thought on “Android Basics – Learn How to Update SQLite Database”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: