ここで、BackupAgents を使用してアプリ データを Google クラウドと同期する Stackoverflow についていくつか質問があります (こちらを参照)。私の特定のケースでは、多かれ少なかれ機密データの性質のために、要件ははるかに制限的です。すべてはデバイス自体にのみ保存する必要があり、アプリはインターネットに接続してはなりません。
メインのアクティビティには、いくつかの ListFragments をホストする ViewPager が含まれています。各 ListFragment には、SimpleCursorAdapter クラスでカーソルを交換する独自のローダーがあります。
データベースのバックアップと復元の両方の前に、次のコマンドでローダーを破棄します。
getLoaderManager().destroy(LOADER_ID);
私のバックアップ機能は、このanwserに似ています:
final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
復元機能は、SD カードから内部アプリ フォルダーにデータベースをコピーし、ローダーを停止してデータベース ファイルを上書きするという点で似ています。
public static void restore(Context context) throws IOException {
if (externalStorageIsWriteable()) {
// getBackupDir() is a path to the folder on the sdcard
File fileBackup = new File(getBackupDir(), WineSQLiteHelper.DB_NAME);
if (!fileBackup.exists()) {
throw new IOException("File not found");
}
File importFile = getImportDatabase();
try {
FileUtils.copyFile(fileBackup, importFile);
MySQLiteHelper dbHelper = new MySQLiteHelper(context);
dbHelper.close();
dbHelper = null;
File file = new File(Environment.getDataDirectory() + "/data/"
+ PACKAGE + "/databases/" + WineSQLiteHelper.DB_NAME);
FileUtils.copyFile(importFile, file);
// Remove temporary import file.
importFile.delete();
} catch (IOException e) {
throw e;
}
} else {
throw new IOException("External Storage not writeable");
}
}
しかし、どういうわけか、データベース ファイルを上書きした後、MainActivity が再作成され、いくつかを受け取りました。
SQLiteException: no such column
私の推測では、データベースへの接続がまだ開かれている可能性がありますが、これほど密接にデータベースを操作しなければならないのはこれが初めてなので、それについてはわかりません。
ContentProvider のすべてのデータベース接続を適切に閉じる方法は? これに関するドキュメントには何も見つかりません。そして、これは必要ですか?
データベースを正しく復元するにはどうすればよいですか?