我有一个带有数据库的应用程序,它是使用标准 SQLiteOpenHelper 创建和打开的。
每当我升级数据库版本时,我也会升级应用程序的版本代码,所以数据库没有办法下降(数据库版本号总是增加,从不减少)。
我通过将 android:allowBackup
属性设置为 false 在我的应用程序中禁用了数据库备份。
但是当我在 Play 商店升级应用程序时,我遇到了很多崩溃
Can't downgrade database from version
n
ton-1
96% 的崩溃发生在运行 .任何人都知道为什么会出现此问题,更重要的是如何防止此崩溃?
我知道我可以覆盖 onDowngrade 以防止崩溃,但我实际上不明白为什么要调用 onDowngrade,因为崩溃是在始终使用最新版本数据库的应用程序上调用的。
编辑:添加代码示例,FWIW
我的 OpenHelper:
public class MyDBHelper extends SQLiteOpenHelper {
private static final String LOG_TAG = MyDBHelper.class.getName();
public static final String DB_NAME = "my_db";
public static final int DB_V1 = 1;
public static final int DB_V2_UNIQUE_IDS = 2;
public static final int DB_V3_METADATAS = 3;
public static final int DB_V4_CORRUPTED_IDS = 4;
public static final int DB_V5_USAGE_TABLE = 5;
public static final int DB_VERSION = DB_V5_USAGE_TABLE;
public MyDBHelper(final Context context, IExceptionLogger logger) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(final SQLiteDatabase db) {
Debug.log_d(DebugConfig.DEFAULT, LOG_TAG, "onCreate()");
db.execSQL(createMyTable());
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
Debug.log_d(DebugConfig.DEFAULT, LOG_TAG, "onUpgrade(): oldVersion = " + oldVersion + " : newVersion = " + newVersion);
if (oldVersion < 2) {
Debug.log_d(DebugConfig.DEFAULT, LOG_TAG, "onUpgrade(): upgrading version 1 table to version 2");
db.execSQL(upgradeTable_v1_to_v2());
}
if (oldVersion < 3) {
Debug.log_d(DebugConfig.DEFAULT, LOG_TAG, "onUpgrade(): upgrading version 2 Entry table to version 3");
db.execSQL(upgradeTable_v2_to_v3());
}
}
@Override
@TargetApi(Build.VERSION_CODES.FROYO)
public void onDowngrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
Debug.log_d(DebugConfig.DEFAULT, LOG_TAG, "onDowngrade(): oldVersion = " + oldVersion + " : newVersion = " + newVersion);
super.onDowngrade(db, oldVersion, newVersion);
}
}
以及我如何初始化它:
public class DatabaseController {
private MyDBHelper mDBHelper;
public void initialize(final Context context) {
mDBHelper = new MyDBHelper(context);
}
}
最佳答案
这是 SQLiteOpenHelper.onDowngrade(...)
的默认实现:
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new SQLiteException("Can't downgrade database from version " +
oldVersion + " to " + newVersion);
}
如您所见,如果您调用 super.onDowngrade(...)
,您将获得该异常。你需要自己实现onDowngrade
,而不是调用super.onDowngrade
。为了完整性,它应该始终被实现,因为不能保证它何时会被调用——用户已经更改为使用旧版本的应用程序听起来很奇怪,但可能会出现这样的情况。您知道异常来自哪个版本的应用程序吗?
关于android - 无法在三星上将数据库从版本 `n` 降级到 `n-1`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200408/