我的当前代码在从资产更新数据库后导致应用程序崩溃(我的数据库格式错误)。我知道问题出在哪里(因为表模式发生了变化),我需要首先通过存储在临时位置来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();
}
btw应用程序在第一次运行应用程序时崩溃,当我再次打开它时,everthing工作正常。如果用户下载最新版本而没有以前的版本,则问题也不会出现。
Logcat:
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)
答案 0 :(得分:0)
如果您确定此代码是正确的,那么如果您没有这样做,请尝试将DATABASE_VERSION = 1;
更改为DATABASE_VERSION = 2;
并尝试这个:
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
答案 1 :(得分:0)
从onUpgrade方法调用copyDatabase()时,您实际上会覆盖现有的数据库文件。问题是,在数据库打开时调用onUpgrade方法,稍后修改它会导致异常。
解决方案可以是在onUpgrade中设置一个标志(比如shouldUpgradeDatabaseFile = true)并在外面执行实际的复制操作(例如在getWritableDatabase()或getReadableDatabase()中)。