Backup and Restore Database android studio

淺唱寂寞╮ 提交于 2019-12-21 06:36:30

问题


I want to make backup and restore for the database in my app, so that when the users delete the application and reinstall it again they can recover their data. What is the best way to do that in Android Studio?


回答1:


There are several types available in back up and restore to your db file like Google drive, drop box and one drive. if you want to do the back up from your local storage try below given code.

Backup code:

  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();
    }
}

Restore code:

  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();
    }
}


来源:https://stackoverflow.com/questions/39770990/backup-and-restore-database-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!