Reputation: 2056
I want the sqlite database of my app to be cleared each time the application is updated. To do that, I make a drop table query on all my tables, in the "onUpgrade" function of SQLiteDatabase.
I got 2 problems: - at the first launch of my app, I don't do any special. - at the second launch, I add a "setVersion(2)" line. It calls the onUpgrade method but the logs are strange:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
Log.d("GDB", "onUpgrade "+oldVersion+" -> "+newVersion);
}
----------------------------------------------------------
DEBUG/GDB(5928): onUpgrade 2 -> 1
So when I make a setVersion(), the 2 versions seems to be switched.....
My second problem is that is I launch my app a third time, without changing the code ( so the setVersion(2) is already here), the onUpgrade method is called again! Did I miss something to definitively set the version to 2?
Upvotes: 1
Views: 3291
Reputation: 2348
I don't think you should be setting the version of the database in code directly using the setVersion method. Instead you should pass the schema version into the constructor of your SQLiteOpenHelper (or at least your class which extends this). Your onUpgrade method should then contain condition statements to decide what to run depending on what version the user is upgrading from. These conditions should form a cascade so that coming from a low version applies in sequence all database updates required to get the user to the current level. So when you want to change your schema, you add a new condition to your onUpgrade and up the schema version passed to your constructor.
This is what the constructor in the OpenHelper looks like:
public TiftHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
Then the onUpgrade looks something like this:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "on upgrade called. Old version:" + oldVersion
+ ". New version:" + newVersion);
if (oldVersion == 19) {
db.execSQL("create table challenges_temp as select * from challenges;");
db.execSQL("drop table challenges;");
db.execSQL(create_challenges);
db.execSQL("insert into challenges (_id, name, is_predef, status) select _id, name, is_predef, 'IN_PROGRESS' from challenges_temp");
db.execSQL("drop table challenges_temp;");
}
if (oldVersion <= 20) {
// adding the status column to the challenges table
db.execSQL("create table challenges_temp as select * from challenges;");
db.execSQL("drop table challenges;");
db.execSQL(create_challenges);
db.execSQL("insert into challenges (_id, name, is_predef, status) select _id, name, is_predef, 'IN_PROGRESS' from challenges_temp");
db.execSQL("drop table challenges_temp;");
}
etc.
That works fine for me.
Upvotes: 3