Search code examples
androidsqliteupgradedatabase-migration

Android SQLiteOpenHelper - how does onUpgrade() work?


Clearly this question has been asked before, but despite looking at several responses, I'm still a bit unsure. The docs for the onUpgrade() method didn't really help either.

Does onUpgrade() get run for each version increment (i.e., from db_v1 to db_v3 onUpgrade() is run once for 1->2, then again for 2->3), or is it just run once (i.e., from db_v1 to db_v3 onUpgrade() is run once for 1->3);

My assumption is that it only is called once. In which case, would something like this work OK?

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    switch (oldVersion) {
    case 0:
        migrateDatabaseToVersion_1(db);
        migrateDatabaseToVersion_2(db);
        migrateDatabaseToVersion_3(db);
        break;
    case 1:
        migrateDatabaseToVersion_2(db);
        migrateDatabaseToVersion_3(db);
        break;
    case 2:
        migrateDatabaseToVersion_3(db);
        break;
    default:
        Log.d(LOG, "no database migrations necessary");
        break;
    }
}

I saw a response here that kind of suggest something similar, but using if statements instead of switch. Any help is much appreciated. Thank you in advance.


Solution

  • The documentation doesn't say this explicitly, but it wouldn't make sense to give both the old and new version numbers as parameters if it would be called for each increment.

    Note: it is preferrable to use a series of if statements instead of a switch: as long as the old version is smaller than the version for the n-th step, upgrade that step. Not only does this avoid duplications, but also prevents you from forgetting a break ...