Reputation: 4699
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?
Upvotes: 0
Views: 2065
Reputation: 2814
Just increment the DATABASE_VERSION
constant then implement the onUpgrade
method to correspond to these changes (e.g., creating the table that was newly added in version 2). One thing to understand is that onUpgrade is not used to upgrade the database version, but to update the database after a version upgrade to catch up with the new version.
Take a look at my source for more info.
Upvotes: 2
Reputation: 1627
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.
Upvotes: 2