I need to upgrade my android sqlite database from version 1 to version 2. But I do not understand how the call public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
is initiated? How and when will this method be called? I don't understand where I pass the Version number 2?
[EDIT] I think I need to clarify this question. Here is my class:
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(Context context){
super(context,
Constants.DB_NAME,
null,
1);
}
public MySQLiteOpenHelper(Context context, int version){
super(context, Constants.DB_NAME, null, version);
}
public MySQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, Constants.DB_NAME, factory, version);
// TODO Auto-generated constructor stub
}
public MySQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version,
DatabaseErrorHandler errorHandler) {
super(context, Constants.DB_NAME, factory, version, errorHandler);
// TODO Auto-generated constructor stub
}
public void onCreate(SQLiteDatabase db) {
// do creation stuff
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// do upgrade stuff
}
}
So, how does android trigger onUpgrade?
The SQLiteOpenHelper
constructor takes a name and version number, and the helper will invoke the onCreate
or onUpgrade
callback as necessary. You need to maintain database version numbers yourself, bumping the version number when a schema change is necessary.
When you need to update your database from version 1 to version 2 just change
super(context, Constants.DB_NAME, null, 1);
to
super(context, Constants.DB_NAME, null, 2);
Then in your onUpgrade
method you drop tables, add tables, or do anything else needed to upgrade from 1 to 2. onUpgrade
will only be invoked the first time the SQLiteOpenHelper is instantiated after the version number changes.