First Android App – DB Upgrade

2 minute read

As a result of adding Text to Speech support to my android application I had to make some changes to the database.  The changes included updating the content to make sure that the text was properly spoken by the text engine.  But this led me to a dilemma as I needed to make sure that those changes were applied to the devices who upgrade to this new version of the application. I thought about adding an option to clear out all data on the application in the preference activity.  But this would mean that users would have their flagged questions removed as well.  There had to be a better and easier way to accomplish this. After doing some research, I found that Android provides an easy way to upgrade a SQLite database.

My application uses an object that extends the SQLiteOpenHelper class to talk to the database that holds the 100 questions and other information.  One of the things you have to specify when creating my object is the version of the database.  I have a static final int variable to hold this.  I use this variable in the constructor of the class (see below):

public class QuestionHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME = "uscis.db";

    /**
     * Points to the latest version of the database. Whenever a
     * new version of the database is made (i.e. schema change, or
     * updating of some data) this value should be increased.
     */
    private static final int SCHEMA_VERSION = 2;

    public QuestionHelper(Context context)
    {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }
}

When you make a change to the database (whether it’s a schema change or an update to the data) and you want these changes to be applied, you must change the version number.  In my case, I had to increment the value of the SCHEMA_VERSION to 2.  Then we have to override the onUpgrade function to add the logic to update the database.

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
     // Note: the new version will always point to
     // the SCHEMA_VERSION variable above.
     if(oldVersion == 1 && newVersion == 2)
     {
         updateQuestionsTableForTTS(db);
     }
}

I hard coded the version numbers above, but you don’t have to do this yourself.  When the application is upgraded, this code will run and update the appropriate tables/data in the database.  By doing this, I avoid the ugly scenario where those users that upgrade the application may loose some of their data (in the case of this application these would be flagged questions).  The more and more I work with Android I am finding that their SDK is a pleasure to work with.  The documentation is great and the examples they give very easy to follow.

Leave a comment