2013-06-28 143 views
0

我目前的代碼導致從資產更新數據庫(我得到的數據庫格式錯誤)後應用程序崩潰。我知道問題出在哪裏(因爲表格模式發生了變化),我需要SELECT *並通過首先存儲在臨時位置來轉儲到新數據庫中,但實際上並不知道如何實現這一點。你能幫我用代碼嗎?SQlite數據庫onUpdate崩潰

目前,它是:

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應用程序崩潰,在第一次運行的應用程序,當我再次打開它寄託都工作正常。如果用戶下載最新版本,而沒有以前的版本,則問題也不會出現。

的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

你可以發佈logcat嗎? – jkau

+0

當然。它已經在那裏 –

回答

0

如果您確信此代碼是正確的,那麼試着改變DATABASE_VERSION = 1;DATABASE_VERSION = 2;如果你沒有做到這一點 也試試這個:

@Override 
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { 
+0

謝謝,我完全像上面那樣..問題是,當我更改數據庫表架構時,提供的代碼崩潰。 –

+0

我想如果你只是你的原始代碼logcat,它會崩潰,它會幫助我和其他人幫助你 – H4F

+0

也有一個「寫錯誤」在我的答案chek它請再次請 – H4F

0

當你可以從onUpgrade方法調用copyDatabase(),你可以有效地重寫現有的數據庫文件。問題在於onUpgrade方法在數據庫處於打開狀態時調用,並且稍後修改它會導致異常。

解決方案可以在onUpgrade中設置一個標誌(如shouldUpgradeDatabaseFile = true)並在外部執行實際的複製操作(例如,在getWritableDatabase()或getReadableDatabase()中)。