备份和还原数据库Android Studio [英] Backup and Restore Database android studio

查看:569
本文介绍了备份和还原数据库Android Studio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序中的数据库进行备份和还原,以便用户删除应用程序并再次重新安装时,他们可以恢复其数据. 在Android Studio中执行此操作的最佳方法是什么?

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?

推荐答案

备份和还原到您的数据库文件中可以使用多种类型,例如Google驱动器,放置框和一个驱动器.如果要从本地存储进行备份,请尝试以下给定的代码.

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.

备份代码:

  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 Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆