To further add missing points here, as per the request by Jaskey
Database version is stored within the SQLite
database file.
catch is the constructor
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
So when the database helper constructor is called with a name
(2nd param), platform checks if the database exists or not and if the database exists, it gets the version information from the database file header and triggers the right call back
As already explained in the older answer, if the database with the name doesn't exists, it triggers onCreate
.
Below explanation explains onUpgrade
case with an example.
Say, your first version of application had the DatabaseHelper
(extending SQLiteOpenHelper
) with constructor passing version as 1
and then you provided an upgraded application with the new source code having version passed as 2
, then automatically when the DatabaseHelper
is constructed, platform triggers onUpgrade
by seeing the file already exists, but the version is lower than the current version which you have passed.
Now say you are planing to give a third version of application with db version as 3
(db version is increased only when database schema is to be modified). In such incremental upgrades, you have to write the upgrade logic from each version incrementally for a better maintainable code
Example pseudo code below:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//upgrade logic from version 1 to 2
case 2:
//upgrade logic from version 2 to 3
case 3:
//upgrade logic from version 3 to 4
break;
default:
throw new IllegalStateException(
"onUpgrade() with unknown oldVersion " + oldVersion);
}
}
Notice the missing break
statement in case 1
and 2
. This is what I mean by incremental upgrade.
Say if the old version is 2
and new version is 4
, then the logic will upgrade the database from 2
to 3
and then to 4
If old version is 3
and new version is 4
, it will just run the upgrade logic for 3
to 4