从资产更新数据库后,我当前的代码导致应用程序崩溃(我得到的数据库格式错误)。我知道问题出在哪里(因为表架构发生了变化),我需要 SELECT * 并首先通过存储在临时位置转储到新数据库中,但真的不知道如何实现这一点。你能帮我写代码吗?
目前是:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
copyDatabase();
} catch (IOException e) {
throw new Error("Error copying database" + e.toString());
}
}
public void copyDatabase() throws IOException {
// Open your local db as the input stream
InputStream myinput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(outfilename);
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer)) > 0) {
myoutput.write(buffer, 0, length);
}
// Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
顺便说一句,应用程序在第一次应用程序运行时崩溃,当我再次打开它时一切正常。如果用户下载最新版本而没有以前的版本,也不会出现此问题。
日志猫:
06-28 17:11:54.456: E/SQLiteLog(25926): (11) database corruption at line 50987 of [00bb9c9ce4]
06-28 17:11:54.456: E/SQLiteLog(25926): (11) statement aborts at 4: [select count(*) from Numerical]
06-28 17:11:54.456: E/DefaultDatabaseErrorHandler(25926): Corruption reported by sqlite on database: /data/data/com.xxx.yyy/databases/database.db
06-28 17:11:54.456: E/DefaultDatabaseErrorHandler(25926): deleting the database file: /data/data/com.xxx.yyy/databases/database.db
06-28 17:11:54.456: E/AndroidRuntime(25926): FATAL EXCEPTION: main
06-28 17:11:54.456: E/AndroidRuntime(25926): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.yyy/com.xxx.yyy.PuzzleActivity}: android.database.sqlite.SQLiteDatabaseCorruptException: database disk image is malformed (code 11)