问题
I'm using ormlite for android and I have a database table class that extends OrmLiteSqliteOpenHelper. I've had some reports in google play that the application had a force close caused by:
android.database.sqlite.SQLiteException: Can't downgrade database from version 3 to 2
The users probably get to downgrade via a backup or something. The problem is I cannot implement the onDowngrade method that exists on SQLiteOpenHelper:
Does ormlite support the downgrade? Is there any work around for this? At least to avoid the force close.
回答1:
Interesting. So the onDowngrade(...)
method was added in API 11. I can't just add support for it into ORMLite. Unfortunately this means that you are going to have to make your own onDowngrade
method which is the same as the onUpgrade(...)
in OrmLiteSqliteOpenHelper
. Something like the followign:
public abstract void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion,
int newVersion) {
// your code goes here
}
public final void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
ConnectionSource cs = getConnectionSource();
/*
* The method is called by Android database helper's get-database calls when Android detects that we need to
* create or update the database. So we have to use the database argument and save a connection to it on the
* AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource().
*/
DatabaseConnection conn = cs.getSpecialConnection();
boolean clearSpecial = false;
if (conn == null) {
conn = new AndroidDatabaseConnection(db, true);
try {
cs.saveSpecialConnection(conn);
clearSpecial = true;
} catch (SQLException e) {
throw new IllegalStateException("Could not save special connection", e);
}
}
try {
onDowngrade(db, cs, oldVersion, newVersion);
} finally {
if (clearSpecial) {
cs.clearSpecialConnection(conn);
}
}
}
For more information about the onDowngrade(...) method see below:
public void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion);
To quote from the javadocs:
Called when the database needs to be downgraded. This is strictly similar to onUpgrade(SQLiteDatabase, int, int) method, but is called whenever current version is newer than requested one. However, this method is not abstract, so it is not mandatory for a customer to implement it. If not overridden, default implementation will reject downgrade and throws SQLiteException
Also see:
Can't downgrade database from version 2 to 1
来源:https://stackoverflow.com/questions/15474116/ormlitesqliteopenhelper-ondowngrade