我有一个带有数据库的应用程序,使用标准 SQLiteOpenHelper 创建和打开。
每当我升级数据库版本时,我也会升级应用程序的版本代码,因此数据库没有办法下降(数据库版本号总是增加,从不减少)。
我通过设置禁用了应用程序中的数据库备份android:allowBackup
属性为 false。
但是当我在 Play 商店升级应用程序时,我遇到了很多崩溃
无法从版本降级数据库n
to n-1
其中 96% 的崩溃发生在运行 .任何人都知道为什么会出现这个问题,更重要的是如何防止这种崩溃?
我知道我可以重写 onDowngrade 以防止崩溃,但实际上我不明白为什么调用 onDowngrade ,因为崩溃是在始终使用数据库最新版本的应用程序上调用的。
Edit:添加了代码示例,FWIW
我的开放助手:
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);
}
}