I\'m trying to backup a room database programmatically.
For that, I\'m simply copying the .sqlite
file that contains the whole database
But, bef
First thing that needs to be done is to create the database with appropriate journal mode.
Room.databaseBuilder(context, AppDatabase::class.java, name)
.setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
.build()
After that the following checkpoint query needs to be executed to ensure all of the pending transactions are applied.
For this a following method needs to be added to the database Dao interface
interface UserDao {
@RawQuery
fun checkpoint(supportSQLiteQuery: SupportSQLiteQuery?): Single<Int>
}
Then the method needs to be called with the following SQL query
userDao.checkpoint((SimpleSQLiteQuery("pragma wal_checkpoint(full)")))
Once the checkpoint method has succeeded the database backup file can finally be saved.
Finally the database backup file can be retrieved using the following code
File(database.openHelper.writableDatabase.path)
The file then needs to be copied into the backup file location.
To restore the file the onky thing that needs to be done is to overwrite the database file (this can be retrieved using above snippet) with the backup file.
You can read about this in more detail on my blog
https://androidexplained.github.io/android/room/2020/10/03/room-backup-restore.html