Copy And Replace Android Database File Programatically (Kotlin)

April 20, 2018
Backup And Restore Android Database By File

Backup/Copy Database File

val DATABASE_NAME = "MyDatabase.db"

// get database absoluate path as file
val inputFile = context.getDatabasePath(DATABASE_NAME).absoluteFile

// create a temp file
val outputFile = File.createTempFile(DATABASE_NAME, null, context.cacheDir)

// copy 
inputFile.copyTo(outputFile, true)

Restore/Replace Database File

// find the exported database file path
val inputFile = ...

// get database absoluate path as file
val outputFile = context.getDatabasePath(DATABASE_NAME).absoluteFile

inputFile.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.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.