SQLiteOpenHelper # onUpgrade () - is the new version still the most recent version?

advertisements

Database Helper with my upgrade idea:

public class DatabaseHelper extends SQLiteOpenHelper {

  private static final String DATABASE_NAME = "myapp.db";
  private static final int DATABASE_VERSION = 11;

  public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  public void onCreate(SQLiteDatabase db) { /* ... */ }

  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch(oldVersion) {
        case 1: upgradeToSecond(db);
        case 2: upgradeToThird();
        case 3: upgradeToFourth();
        // ...
        case 10: upgradeToEleventh();
    }
  }

  private void upgradeToSecond(SQLiteDatabase  db) { /* ... */ }
  private void upgradeToThird(SQLiteDatabase  db) { /* ... */ }
  private void upgradeToFourth(SQLiteDatabase  db) { /* ... */ }
  // ...
  private void upgradeToEleventh(SQLiteDatabase  db) { /* ... */ }
}

Thanks to the switch without breaks, database schema will be updated step by step to the newest version, no matter what version user had before. If the oldVersion is 8, the upgrade methods upgradeToNinth(db), upgradeToTenth(db) and upgradeToEleventh(db) will be run. Great!

But this code makes an assumption that the value of newVersion is always the newest version of the database (the value supplied to the SQLiteOpenHelper constructor). Is this alwyas true? Are there cases when onUpgrade method is called with newVersion other that the newest one?


But this code makes an assumption that the value of newVersion is always the newest version of the database (the value supplied to the SQLiteOpenHelper constructor). Is this alwyas true?

Yes.

This can be verified by reading the source where onUpgrade() is called with newVersion argument being the same you passed in as the argument to SQLiteOpenHelper constructor.