Upgrade Android SQLite Database

After fiddling with a few different styles of coding a database upgrade implementation for Android, I’ve settled on a fairly simple method.  Basically, I take the old version, and increment a counter until I get to the current version.  Through each iteration, I use switch on the value of the upgradeTo variable, and upgrade each cycle.  If things get too complex for your application, you can always create individual upgrade methods, for each version.

Of course this method will only work if your database version is incremented by one each time you change the database.  And, this really should be the way you version it anyhow.

    public void onUpgrade(
        final SQLiteDatabase db, final int oldVersion,
        final int newVersion)
    {
        int upgradeTo = oldVersion + 1;
        while (upgradeTo <= newVersion)
        {
            switch (upgradeTo)
            {
                case 5:
                    db.execSQL(SQLiteSet.V5_ADD_LAST_CARD);
                    db.execSQL(SQLiteCard.V5_ADD_FAILED);
                    break;
                case 6:
                    db.execSQL(SQLiteSet.V6_ADD_IMPORT_TYPE);
                    break;
                case 7:
                    db.execSQL(SQLiteSet.V7_ADD_SHORT_FNAME);
                    break;
            }
            upgradeTo++;
        }
    }

Someone asked in a comment, why we do the upgrade in a loop.  I do this because I do not know what version they will be converted from or to. So, I must either put a bunch of logic for every possible upgrade variation, such as 1 => 2, 1 => 3, 1=> 4, 3=> 4, etc, etc, or, I can loop through and do one upgrade at a time, and increment the version through each loop.  This GREATLY simplifies the database upgrade.