Nouvel Travay Nouvel Travay - 2 months ago 9
Android Question

Adding new table to sqlite

For SQLiteOpenHelper, if I add a new table inside

onCreate
do I have to do anything inside
onUpgrade
? I am adding a completely new table. I believe I have to change the version number but that
onUpgrade
should remain empty. Is that correct?

Answer

If you want existing installs of the app to add this new table, then yes, you must increase the version and provide a suitable onUpgrade() implementation, as well as adding the table in onCreate() (which you stated you have already done).

An empty onUpgrade() implementation is not sufficient; it has to actually do something. Some people drop all tables and just call onCreate() directly, but this obviously doesn't work well if you are trying to keep existing data. I usually use the fall-through switch idiom, so that if a user is more than one version behind (e.g. you publish a version 3 and a user is still on version 1) they will go through all the necessary upgrades sequentially:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
        case 1:
            db.execSQL("CREATE TABLE " + ...);
            // no break statement, so case 2 will execute after this.
        case 2:
            // more execSQL(), etc
    }
}