【问题标题】:how to backup database in Android 9 (Pie)?如何在 Android 9 (Pie) 中备份数据库?
【发布时间】:2019-12-09 06:49:55
【问题描述】:

我有一个备份活动,用户可以备份应用程序数据库并在以后恢复它... 对于备份,我只是将我的应用程序 database.db 文件复制到 sdcard ... 为了恢复,我首先删除 database.db-shm 和 database.db-wal 文件(如果存在)(因为 android 9 使用它们),然后用新的替换 database.db。

恢复功能在所有 android 版本中都能正常工作。 备份功能也适用于所有android版本,但在android 9.0中它不可靠! 因为用户添加的一些新数据在缓存文件(database.db-shm 和 database.db-wal)中,并没有应用于 database.db

我该怎么办?

我可以强制将缓存文件应用到database.db然后备份吗?

或者...

【问题讨论】:

    标签: database backup shared-memory


    【解决方案1】:

    我自己回答...

    通过此链接:Temporary Files Used By SQLite

    说: “WAL 文件是在打开与数据库的第一个连接时创建的,通常会在与数据库的最后一个连接关闭时删除。但是,如果最后一个连接没有完全关闭,WAL 文件将保留在文件系统中,并将被下次打开数据库时自动清理。"

    所以我在备份前关闭数据库,备份后再次打开它

    protected void backupDB() throws IOException {
        SugarContext.terminate(); //Close databse
        String format = new SimpleDateFormat("_yyyyMMdd-HHmmss").format(new Date());
        FileInputStream indb = new FileInputStream(new File(new File(Environment.getDataDirectory() + File.separator + "//data//ir.shia.mohasebe//databases//"), "sugar_example.db"));
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Mohasebe Amal");
        file.mkdirs();
        FileOutputStream outdb = new FileOutputStream(new File(file, "mohasebe_backup" + format + ".mbac"));
        FileChannel channel = indb.getChannel();
        FileChannel channel2 = outdb.getChannel();
        channel2.transferFrom(channel, 0, ((FileChannel) channel).size());
        channel.close();
        channel2.close();
        SugarContext.init(getApplicationContext()); //Open database again
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      相关资源
      最近更新 更多