如何在 SD 卡上备份和恢复 SqliteDatabase、SharedPreferences - Android
How to backup & restore SqliteDatabase,SharedPreferences on SD-Card - Android
您好,我正在开发一个应用程序,我在其中将数据存储到 Sqlite
& SharedPrefrences
。我从 android 文档中学习,他们说我们可以通过注册服务来做到这一点,但我认为这仅适用于云存储,因为我想在 SD 卡上备份数据。我也找过 FileBackHelper,但没有给出任何说明。
请说出实施它的最佳方式是什么?
您可以像这样将 sqlite 数据库复制到 sdcard
private void exportDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "com.your.package" +"/databases/"+db_name;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
共享首选项文件位置主要由设备制造商选择,因此对任何共享首选项文件的路径进行硬编码是不好的。
您好,我正在开发一个应用程序,我在其中将数据存储到 Sqlite
& SharedPrefrences
。我从 android 文档中学习,他们说我们可以通过注册服务来做到这一点,但我认为这仅适用于云存储,因为我想在 SD 卡上备份数据。我也找过 FileBackHelper,但没有给出任何说明。
请说出实施它的最佳方式是什么?
您可以像这样将 sqlite 数据库复制到 sdcard
private void exportDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "com.your.package" +"/databases/"+db_name;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
共享首选项文件位置主要由设备制造商选择,因此对任何共享首选项文件的路径进行硬编码是不好的。