我正在尝试将 sqlite 版本号从 1 升级到 2,但是没有调用 onupgrade 方法。
我是否必须删除设备中的应用程序,然后安装该应用程序才能对其进行测试?
唯一被调用的方法是 DatabaseHelper
和 onCreate
没有其他方法被调用。
在DatabaseHelper.java文件中
private static final int DBVersion = 1; // I had change this value to 2.but it is not working.
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE_Table);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
//This is not called.If it called i will add the changed here
}
dataprovider.java 的另一个类
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
return true;
}
最佳答案
使用:-
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
SqliteDatabase db = dbHelper.getWritableDatabase(); //<<<<<<<<<<<
return true;
}
尝试打开数据库,因此将调用 onCreate/onUpgrade。 - onCreate 仅当数据库不存在时。 - onUpgrade 仅当数据库存在且指定的版本号大于数据库中存储的数据库版本时。
也就是说,当实例化数据库助手(SQLiteOpenHelper 的子类)时,不会尝试打开数据库。
仅当调用 SQLiteDatabase 的 getWritableDatabase(或 getReadableDatabase)时才会尝试打开数据库。两者都尝试打开数据库。注意 getWritableDatabase 或 getReadableDatabase 可能会被隐式调用。
- 注意以上不包括直接使用 SQliteDatabase 的 OPEN 方法。
替代修复
在构建数据库助手时,我个人倾向于强制打开:-
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
this.getWritableDatabase();
}
- 我倾向于将返回的 SQLiteDatabase 保存到一个类变量中,然后使用它,而不是在底层方法中使用
this.getWritableDatabase()
。
关于android - 在android studio中升级数据库不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484837/