私は ORMLite を使用しており、データベースを外部パブリック ディレクトリに保存する以外に、ファイルをデータベース ディレクトリに復元した後、DatabaseHelper
シングルトンを再インスタンス化して新しいものを作成する必要があります。
これが私のバージョンで、簡単にするためにすべての try/catch ブロックを省略しています。
public boolean restoreBackup(Context context){
String databasePath = "data/data/my.package.name/databases/myDatabase.sqlite";
String backUpPath = context.getDatabaseDir("myDatabase.sqlite");
// Copies back-up to database directory
new File(databasePath).delete();
FileInputStream streemToBackUp = new FileInputStream(new File(backUpPath));
OutputStream streamToDatabaseFile = new FileOutputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = streamToBackUp.read(buffer)) > 0) {
streamToDatabaseFile.write(buffer, 0, length);
}
streamToDatabaseFile.flush();
streamToDatabaseFile.close();
streamToBackUp.close();
// Re-instantiate DatabasHelper singleton
DatabaseHelper.closeHelper();
}
の本体closeHelper()
は次のとおりです。
public static void closeHelper() {
helper.close();
}
@Override
public void close() {
super.close();
myDao = null; // Set to null every day you have
helper = null; // Set to null the singleton instance of the helper
}
これは、 OpenHelperManagerクラスを使用してヘルパーをインスタンス化しない限り機能しgetHelper()
、返されたインスタンスを格納する代わりにデータベースが必要な場合は常に使用します。