android - 备份和恢复数据库android studio

标签 android database sqlite backup recover

我想在我的应用程序中对数据库进行备份和恢复,这样当用户删除应用程序并重新安装时,他们可以恢复他们的数据。 在 Android Studio 中最好的方法是什么?

最佳答案

有多种类型可用于备份和恢复到您的数据库文件,例如 Google 驱动器、保管箱和一个驱动器。如果您想从本地存储进行备份,请尝试下面给出的代码。

备份代码:

  public void backUp() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//your package     name//databases//dbname.db";
            String backupDBPath = "dbname.db";

            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            Log.d("backupDB path", "" + backupDB.getAbsolutePath());

            if (currentDB.exists()) {
                FileChannel src = new     FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getApplicationContext(), "Backup is successful to SD card", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

恢复代码:

  public void restore() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//your package name//databases//dbname.db";;
            String backupDBPath = "dbname.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(backupDB).getChannel();
                FileChannel dst = new FileOutputStream(currentDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

关于android - 备份和恢复数据库android studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770990/

相关文章:

Android 多个WebView保存实例

c# - 使用 SQL Server 的本地数据库

android - Android sqlite数据库访问引发锁定错误

android - 我们如何使表格布局双向滚动(水平,垂直)

java - android 按钮可以执行另一个按钮然后执行它自己的代码吗?

android - 如何将位图设置为从相机捕获的 main.xml 中的 ImageView?

java - @SequenceGenerator allocationSize 'duplicate key error' 问题

database - akinator 正在与数据库一起运行?

java - 使用 double 值(纬度/经度)过滤器更新 sqlite 行不起作用

sqlite - 无法使用类型的参数列表调用 'insert'