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?
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:
Then the onUpgrade looks something like this:
etc.
That works fine for me.