Copy And Replace Android Database File Programatically (Kotlin)

Apr 20, 2018
Backup And Restore Android Database By File

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.