Backup Room database

后端 未结 7 766
夕颜
夕颜 2020-12-08 01:41

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

相关标签:
7条回答
  • 2020-12-08 02:12

    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

    0 讨论(0)
提交回复
热议问题