Backup/Copy Database File
val DATABASE_NAME = "MyDatabase.db"// get database absoluate path as fileval inputFile = context.getDatabasePath(DATABASE_NAME).absoluteFile// create a temp fileval outputFile = File.createTempFile(DATABASE_NAME, null, context.cacheDir)// copy inputFile.copyTo(outputFile, true)
Restore/Replace Database File
// find the exported database file pathval inputFile = ...// get database absoluate path as fileval outputFile = context.getDatabasePath(DATABASE_NAME).absoluteFileinputFile.copyTo(outputFile, true)// inputFile.delete()
NOTE: I am using Room with LiveData. The LiveData
event is fired when database is replaced on some device (I assuming depending on Android version), but not all devices. I guess it would be best practice to restart the activity or app when the database file is replaced.
NOTE: I tested on Mashmallow, Nougat and ICS.