[英]Copying Database from Assets Folder into app
我已在線上關注了許多教程,這些教程如何實現將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);
也許上下文是通過錯誤傳遞的,但我看不出是怎么回事。
您使用常規文件操作復制數據庫,而錯誤消息顯然指向sqlite
。 因此,當您嘗試打開不存在的數據庫時,很可能發生該錯誤。 如果有堆棧跟蹤,它將確切顯示它發生的位置。
最后,我建議您不要使用Error
類,因為它是為VM錯誤保留的。 使用RuntimeException
並始終在其中包含根本原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.