I want to add a function to export the database file, upload it to Firebase storage, and then, with a click, download the database file and replace (or import) it to the current database.
I don't know if my way is the best or not, but this is code that I am trying to work on it. This code is trying to save the database to the SD card (external storage).
I don’t need to use WRITE_EXTERNAL_STORAGE and don't have any need to save on local storage. Just Firebase storage, directly. Plus, I did not test this code yet, because my phone is Android 11 and WRITE_EXTERNAL_STORAGE is not working on it. So maybe the code is not working at all, I don't know.
private fun importDB() {
try {
val sd = Environment.getExternalStorageDirectory()
val data = Environment.getDataDirectory()
if (sd.canWrite()) {
val currentDBPath = ("//data//" + "PackageName"
+ "//databases//" + "DatabaseName")
val backupDBPath = "/BackupFolder/DatabaseName"
val backupDB = File(data, currentDBPath)
val currentDB = File(sd, backupDBPath)
val src = FileInputStream(currentDB).channel
val dst = FileOutputStream(backupDB).channel
dst.transferFrom(src, 0, src.size())
src.close()
dst.close()
Toast.makeText(
baseContext, backupDB.toString(),
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
Toast.makeText(baseContext, e.toString(), Toast.LENGTH_LONG)
.show()
}
}
//exporting database
private fun exportDB() {
val storageRef = FirebaseStorage.getInstance().reference
.child("database/${FirebaseAuth.getInstance().currentUser?.uid}")
try {
val sd = Environment.getExternalStorageDirectory()
val data = Environment.getDataDirectory()
if (sd.canWrite()) {
val currentDBPath = ("//data//" + "PackageName"
+ "//databases//" + "DatabaseName")
val backupDBPath = "/BackupFolder/DatabaseName"
val currentDB = File(data, currentDBPath)
val backupDB = File(sd, backupDBPath)
val src = FileInputStream(currentDB).channel
val dst = FileOutputStream(backupDB).channel
dst.transferFrom(src, 0, src.size())
src.close()
dst.close()
Toast.makeText(
baseContext, backupDB.toString(),
Toast.LENGTH_LONG
).show()
}
} catch (e: Exception) {
Toast.makeText(baseContext, e.toString(), Toast.LENGTH_LONG)
.show()
}
}