我正在我的Android应用中实现备份/恢复系统。
自动备份每隔几分钟进行一次。我试图在我的SD卡上从db备份文件中恢复,之后再次卸载和安装我的应用程序。
备份工作正常,但是问题来了:
每当用户重新安装我的应用程序时,都会出现文件未找到异常。但是,如果用户关闭应用程序,然后再次打开它,恢复就可以正常运行。不知何故,在应用程序首次启动时恢复会遇到问题。
恢复必须在第一次启动时发生。
注意:backupExists函数返回true。
自动备份每隔几分钟进行一次。我试图在我的SD卡上从db备份文件中恢复,之后再次卸载和安装我的应用程序。
备份工作正常,但是问题来了:
每当用户重新安装我的应用程序时,都会出现文件未找到异常。但是,如果用户关闭应用程序,然后再次打开它,恢复就可以正常运行。不知何故,在应用程序首次启动时恢复会遇到问题。
恢复必须在第一次启动时发生。
注意:backupExists函数返回true。
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(backUpExists()){
restoreDB();
}
}
private boolean backUpExists()
{
try{
File sd = Environment.getExternalStorageDirectory();
if (sd.canRead()){
String backupDBPath = "myDB";
File backupedDB = new File(sd, backupDBPath);
if(backupedDB.exists()){
return true;
}
}
} catch(Exception ex) {
Toast.makeText(getBaseContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
return false;
}
private void restoreDB()
{
try{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String restroredDBPath = "//data//myPackage//databases//myDB";
String backupDBPath = "myDB";
File restoredDB = new File(data, restroredDBPath);
File backupedDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(backupedDB).getChannel();
FileChannel dst = new FileOutputStream(restoredDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), restoredDB.toString(), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
回溯
09-09 22:49:50.931: I/Database(23206): sqlite returned: error code = 26, msg = statement aborts at 14: [SELECT COUNT(*) FROM Photos WHERE AlbumId=0] file is encrypted or is not a database
09-09 22:49:50.931: D/AndroidRuntime(23206): Shutting down VM
09-09 22:49:50.931: W/dalvikvm(23206): threadid=1: thread exiting with uncaught exception (group=0x4151c700)
09-09 22:49:50.931: E/AndroidRuntime(23206): FATAL EXCEPTION: main
09-09 22:49:50.931: E/AndroidRuntime(23206): net.sqlcipher.database.SQLiteException: file is encrypted or is not a database
09-09 22:49:50.931: E/AndroidRuntime(23206): at net.sqlcipher.database.SQLiteQuery.native_fill_window(Native Method)
09-09 22:49:50.931: E/AndroidRuntime(23206): at net.sqlcipher.database.SQLiteQuery.fillWindow(SQLiteQuery.java:73)
09-09 22:49:50.931: E/AndroidRuntime(23206): at net.sqlcipher.database.SQLiteCursor.fillWindow(SQLiteCursor.java:290)
[snipped]
try
/catch
以获取正确的堆栈跟踪。 - CL.