你能替换android数据库吗?

时间:2017-10-08 18:16:12

标签: android

我是android studio的新手,我正在尝试从我的应用程序备份我的数据库。我可以从数据/数据/数据库中提取database.db,但是当我清除数据并尝试将db的副本导入数据/数据/数据库时,没有任何事情发生。

问题是你不能修改数据/数据/数据库吗?

1 个答案:

答案 0 :(得分:0)

这是备份和恢复数据库的代码

 private void importDB() {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();
                if (sd.canWrite()) {
                String currentDBPath = "//data//" + "<package name>"
                        + "//databases//" + "<database name>";
                String backupDBPath = "<backup db filename>"; 
                File backupDB = new File(data, currentDBPath);
                File currentDB = new File(sd, backupDBPath);

            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(), "Import Successful!",
                    Toast.LENGTH_SHORT).show();

        }
    } catch (Exception e) {

        Toast.makeText(getApplicationContext(), "Import Failed", Toast.LENGTH_SHORT)
                .show();

    }
}

private void exportDB() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

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

            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 Successful!",
                    Toast.LENGTH_SHORT).show();

        }
    } catch (Exception e) {

        Toast.makeText(getApplicationContext(), "Backup Failed", Toast.LENGTH_SHORT)
                .show();

    }
}