Android - Database upgrade strategy for the extended class of SQLiteOpenHelper

By xngo on February 26, 2019

On the Android platform, upgrading database on the mobile devices is a tricky business. Not all devices are running on the same version. Therefore, you have to provide a way to do incremental upgrade on each individual device depending on their version.

An approach would be to use the switch statement inside your onUpgrade() function of your extended SQLiteOpenHelper class.

Here is an example using the switch to incrementally upgrade up to version 5. It is purely using the full potential of the Java switch statement.

public class DBHelper extends SQLiteOpenHelper {
 
    private static final String dbName="mydatabase.db";
    private static final int dbVersion=5; // Latest version number.
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
        int version=oldVersion+1;
 
        switch(version) {
            case 2: System.out.println("Run changes for version 2.");
            case 3: System.out.println("Run changes for version 3.");
            case 4: System.out.println("Run changes for version 4.");
            case 5: System.out.println("Run changes for version 5.");
                break;
            default:
                System.out.println("Version number not supported!");
                break;
        }
    }
}

Notes:

  • oldVersion is the version on the device.
  • dbVersion should match your latest case, i.e. 5.

If the device is on version 3, then it will execute statements in case 4 and 5. The output will be:

  1. Run changes for version 4.
  2. Run changes for version 5.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.