Skip to content

Instantly share code, notes, and snippets.

@varundwarkani
Created May 8, 2020 17:42
Show Gist options
  • Save varundwarkani/d86390e6d6822ac20ea271326cf3fb4a to your computer and use it in GitHub Desktop.
Save varundwarkani/d86390e6d6822ac20ea271326cf3fb4a to your computer and use it in GitHub Desktop.
Backup Room Database Method in Android
public static void backupDatabase(Context context) {
AppDatabase appDatabase = AppDatabase.getAppDatabase(context);
appDatabase.close();
File dbfile = context.getDatabasePath(DATABASE_NAME);
File sdir = new File(getFilePath(context, 0), "backup");
String fileName = FILE_NAME + getDateFromMillisForBackup(System.currentTimeMillis());
String sfpath = sdir.getPath() + File.separator + fileName;
if (!sdir.exists()) {
sdir.mkdirs();
} else {
//Directory Exists. Delete a file if count is 5 already. Because we will be creating a new.
//This will create a conflict if the last backup file was also on the same date. In that case,
//we will reduce it to 4 with the function call but the below code will again delete one more file.
checkAndDeleteBackupFile(sdir, sfpath);
}
File savefile = new File(sfpath);
if (savefile.exists()) {
Log.d(LOGGER, "File exists. Deleting it and then creating new file.");
savefile.delete();
}
try {
if (savefile.createNewFile()) {
int buffersize = 8 * 1024;
byte[] buffer = new byte[buffersize];
int bytes_read = buffersize;
OutputStream savedb = new FileOutputStream(sfpath);
InputStream indb = new FileInputStream(dbfile);
while ((bytes_read = indb.read(buffer, 0, buffersize)) > 0) {
savedb.write(buffer, 0, bytes_read);
}
savedb.flush();
indb.close();
savedb.close();
SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREDPREF, MODE_PRIVATE);
sharedPreferences.edit().putString("backupFileName", fileName).apply();
updateLastBackupTime(sharedPreferences);
}
} catch (Exception e) {
e.printStackTrace();
Log.d(LOGGER, "ex: " + e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment