Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDowngrade() in SQLiteOpenHelper (or another way to not crash when downgrading)

Very new to Java. Working with my app, and decided, I'd drop my DATABASE_VERSION back down to 1 (no real reason).

When I started the app, it crashed, and one of the errors was:

E/AndroidRuntime(14905): Caused by: android.database.sqlite.SQLiteException: Can't downgrade database from version 17 to 4

E/AndroidRuntime(14905): at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:307)

I already have an onUpgrade(), where I delete the tables then runs the onCreate()... so I thought I'd make an onDowngrade():

@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onUpgrade(db);
}

But apparently that's not a superclass method that I can override.

Is there a way (easy way hopefully) to allow me to change the database version to any number I want and have it still run without crashing immediately?

like image 383
Dave Avatar asked Dec 27 '22 21:12

Dave


1 Answers

Is there a way (easy way hopefully) to allow me to change the database version to any number I want and have it still run without crashing immediately?

In development, simply get rid of your database, either via the Clear Data button for your app in Settings, or by uninstalling the app from settings, or by wiping the whole emulator (if this is an emulator). Your database will be created anew on next run via a call to onCreate() in your SQLiteOpenHelper.

In production, as rciovati noted, the concept of supporting a downgrade was only introduced with API Level 11, and I have never tried it personally.

like image 107
CommonsWare Avatar answered May 06 '23 13:05

CommonsWare