2011-08-01 41 views
0

我已經在線學習了很多關於如何將apk文件夾中的「assets」文件夾複製到應用程序的「/ data/data // databases」文件夾的教程。使用我的代碼,第一次打開它並複製數據庫時失敗。將資產文件夾中的數據庫複製到應用程序中

就像教程中說的那樣,它會創建一個空的數據庫,在該數據庫中我的數據庫被複制進來,但它似乎不適用於我。代碼與其他地方完全一樣。但是無論如何,這都是適當的日誌。

public void createDataBase() throws IOException{ 

     boolean dbExist = checkDataBase(); 
     SQLiteDatabase db_Read = null; 

     if(dbExist){ 
      //do nothing - database already exist 
      Log.v("DBHandler", "Database does exist"); 
     }else{ 
      //By calling this method and empty database will be created into the default system path 
      //of your application so we are gonna be able to overwrite that database with our database. 
      Log.v("DBHandler", "Database does not exist"); 

      db_Read = this.getReadableDatabase(); 
      db_Read.close(); 

     try { 
       copyDataBase(); 
      } catch (IOException e) { 
       throw new Error("error copying database"); //Error gets thrown here 
      } 
     } 

    } 


private 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 bytes from the inputfile to the 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(); 

} 

我得到在日誌下面的錯誤:

08-01 14:34:25.046: ERROR/Database(27530): sqlite3_open_v2("/data/data/com.package/databases/DB.sqlite", &handle, 1, NULL) failed 

我很肯定的錯誤是在數據庫上的複製。如果需要更多信息,我會很樂意提供。

編輯:我相信錯誤是在複製數據庫,所有的路徑目錄都是正確的。我認爲它與該行有關係:InputStream myInput = myContext.getAssets().open(DB_NAME);可能通過錯誤傳遞的上下文,但我看不到如何。

+0

請仔細檢查您的代碼(以及您的問題)。你把它複製到「數據/數據/數據庫」?你確定DB_NAME是否與你的路徑中的數據庫相匹配,或者你是否複製並粘貼示例代碼?你確定DB_PATH是你想要放置數據庫的位置嗎? –

+0

@Nathan Fig:是的,我確定路徑是正確的,代碼適用於我的手機它在模擬器中,我收到這些錯誤。我聽說一些設備在打開數據庫方面的工作方式不同,並且遇到類似於其他應用程序的問題。 – SamRowley

+0

我只是試圖將數據庫文件複製到SD卡,我可以從那裏打開它沒有問題。這有什麼理由是一個壞主意嗎? – Kurru

回答

0

您使用常規文件操作複製數據庫,而錯誤消息明確指代sqlite。因此,當您嘗試打開不存在的數據庫時,最有可能發生該錯誤。如果有堆棧跟蹤,它會顯示它發生的確切位置。

最後,我建議您不要使用類Error,因爲它保留給VM錯誤。使用RuntimeException並始終包含根本原因。

相關問題