我在我的应用程序中使用了预填充的sqlite数据库,并且我试图在我的安卓应用程序中更新我的数据库,但是当我递增版本号时,onUpgrade
方法不会被调用。我试着用谷歌搜索,在stackoverflow上搜索,但都没有帮助。如果我在构造函数中取消对this.getReadableDatabase()
的注释,onUpgrade
方法将被调用,但我无法查询数据并返回错误。
这是我的代码。
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "dictionary.db";
private static final int DB_VERSION = 1;
private String DB_PATH = null;
private static final String TABLE_DICTIONARY = "dictionary";
private static final String TABLE_BOOKMARK= "bookmark";
private static final String COL_ID = "id";
private static final String COL_WORD = "word";
private static final String COL_DEFINITION = "definition";
private Context mcontext;
private SQLiteDatabase mDatabase;
public DatabaseHelper( Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.mcontext = context;
this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
//this.getReadableDatabase();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
mcontext.deleteDatabase(DB_NAME);
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQ
LiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = mcontext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
mDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (mDatabase != null)
mDatabase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "onUpgrade:called ");
}
}
https://stackoverflow.com/questions/55711282
复制相似问题