Backup Room database

后端 未结 7 764
夕颜
夕颜 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 01:49

    It already has been answered above. No need to close/re-open database.

    I am using MVVM pattern in my android app to back up db file to upload it to google drive. Just want to summarise the solution that worked for me:

    Mention below code in your DAO file:

    @RawQuery
        int checkpoint(SupportSQLiteQuery supportSQLiteQuery);
    

    Mention below code in your repository file:

        /* Android database has three files under /data/data/com.package.app/databases/
        ** test.db, test.db-shm, test.db-wal - those extra files have recent commits.
        ** To merge data from other shm and wal files to db, run following method - useful before taking backup.
        */
        void checkPoint() {
            ItemRoomDatabase.databaseWriteExecutor.execute(() -> {
               itemDao.checkpoint(new SimpleSQLiteQuery("pragma wal_checkpoint(full)"));
            });
        }
    

    mention following in your ViewModel:

    public void checkPoint() {
          itemRepository.checkPoint();
    }
    

    Now you can call this method just before doing backup from your Activity file

    ItemViewModel itemViewModel = new ViewModelProvider(this).get(ItemViewModel.class);
    itemViewModel.checkPoint();
    

提交回复
热议问题