我决定更新我的应用程序及其数据库,但是在执行下面的代码并运行应用程序之后,我以一种奇怪的方式复制了数据库——有些部分被复制了,有些则没有。
最让我困惑的是,一切都在模拟器上完美运行,而在我的 Nexus 上却出现了问题。
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();
}