【问题标题】:Backup and Restore Database android studio备份和恢复数据库 android studio
【发布时间】:2016-09-29 12:57:03
【问题描述】:

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

【问题讨论】:

    标签: android database sqlite backup recover


    【解决方案1】:

    有多种类型可用于备份和恢复到您的数据库文件,例如 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();
        }
    }
    

    【讨论】:

    • 为什么在路径中使用双斜杠//?最好不要对路径进行硬编码,而是使用例如context.getDatabasePath(DataBaseHelper.dbName)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多