备份和恢复数据库android studio

时间:2016-09-29 12:57:04

标签: android database sqlite backup recover

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

1 个答案:

答案 0 :(得分:2)

有几种类型可用于备份和还原到您的db文件,如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();
    }
}