I have an existing database based on SQLiteOpenHelper
that has several versions and code to update it, and this works fine. But if the user installs an older version of the application (which expects a lower version of the database), it is currently crashing - using ContentProvider
with it cannot access the database. I would like to prevent it from crashing, but I don't want to actually downgrade the database - adding code for this would be a pain. Deleting all tables will certainly work, but starting with a new file, you will clear and reduce the likelihood of errors.
What about what the database helper looks like - nothing special
public class MyDbHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 3; private static final String DATABASE_NAME = "my.db"; public MyDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { onUpgrade(db, 0, DATABASE_VERSION); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion < 1) db.execSQL("CREATE TABLE A..."); if (newVersion < 2) db.execSQL("CREATE TABLE B..."); if (newVersion < 3) db.execSQL("CREATE TABLE C..."); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Possible ways that I did for this:
- Do it from the outside: catch the exceptions in the
ContentProvider
, delete the file and ask to open the database again. - I do not like this, because it is not the responsibility of the provider. - Replacing
SQLiteOpenHelper
my own copy of this class, which deletes the file instead of calling onDowngrade
. The problem is that it uses private parts of the SQLiteDatabase
package (for example, .lock()
), which I cannot replace without duplicating SQLiteDatabase
too (which will probably lead to duplication of the entire sqlite package).
Is there any good approach to this, or do I need to follow the DROP TABLES
path, for example. as described here ?
source share