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.