To more specifically answer your question, this is how I backup the room database in one of my Apps.
1-Check for permission to read from / write to the external storage.
2-Close your RoomDatabase. In my case AppDatabase refers to a singleton that contains logic for building the room database initially. AppDatabase.getInstance(this@MainActivity) gets the current instance of the singleton, and its current database class, that extends from RoomDatabase.
3-Then essentially call dbInstance.close().
private fun createBackup() {
val db = AppDatabase.getInstance(this@MainActivity)
db.close()
val dbFile: File = getDatabasePath(DATABASE_NAME)
val sDir = File(Environment.getExternalStorageDirectory(), "Backup")
val fileName = "Backup (${getDateTimeFromMillis(System.currentTimeMillis(), "dd-MM-yyyy-hh:mm")})"
val sfPath = sDir.path + File.separator + fileName
if (!sDir.exists()) {
sDir.mkdirs()
}
val saveFile = File(sfPath)
if (saveFile.exists()) {
Log.d("LOGGER ", "File exists. Deleting it and then creating new file.")
saveFile.delete()
}
try {
if (saveFile.createNewFile()) {
val bufferSize = 8 * 1024
val buffer = ByteArray(bufferSize)
var bytesRead: Int
val saveDb: OutputStream = FileOutputStream(sfPath)
val indDb: InputStream = FileInputStream(dbFile)
do {
bytesRead = indDb.read(buffer, 0, bufferSize)
if (bytesRead < 0)
break
saveDb.write(buffer, 0, bytesRead)
} while (true)
saveDb.flush()
indDb.close()
saveDb.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
You have to include save file in
try {
//backup process
}
} catch (e: Exception) {
e.printStackTrace()
}
in order of any error occur and to avoid app crashes.
And to get date from currentTimeMillis
use this function
fun getDateTimeFromMillis(millis: Long, pattern: String): String {
val simpleDateFormat = SimpleDateFormat(pattern, Locale.getDefault()).format(Date())
return simpleDateFormat.format(millis)
}
The Code For Resoting Db
passing file object to Uri.fromFile
try {
val fileUri: Uri = Uri.fromFile(file)
val inputStream = contentResolver.openInputStream(fileUri)
println("restoring ")
restoreDatabase(inputStream);
inputStream?.close()
} catch (e: IOException) {
println( e.message)
e.printStackTrace()
}
**Or returning result with start activity for result **
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 12 && resultCode == RESULT_OK && data != null) {
Uri fileUri = data.getData();
try {
assert fileUri != null;
InputStream inputStream = getContentResolver().openInputStream(fileUri);
restoreDatabase(inputStream);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
restoreDatabase function
private fun restoreDatabase(inputStreamNewDB: InputStream?) {
val db = AppDatabase.getInstance(this@MainActivity)
db.close()
val oldDB = getDatabasePath(DATABASE_NAME)
if (inputStreamNewDB != null) {
try {
copyFile(inputStreamNewDB as FileInputStream?, FileOutputStream(oldDB))
println("restore success")
} catch (e: IOException) {
Log.d("BindingContextFactory ", "ex for is of restore: $e")
e.printStackTrace()
}
} else {
Log.d("BindingContextFactory ", "Restore - file does not exists")
}
}
now you need to copy file from backup into real db file
use copyFile
@Throws(IOException::class)
fun copyFile(fromFile: FileInputStream?, toFile: FileOutputStream) {
var fromChannel: FileChannel? = null
var toChannel: FileChannel? = null
try {
fromChannel = fromFile?.channel
toChannel = toFile.channel
fromChannel?.transferTo(0, fromChannel.size(), toChannel)
} finally {
try {
fromChannel?.close()
} finally {
toChannel?.close()
}
}
}