【发布时间】:2018-11-30 07:51:24
【问题描述】:
- 如何备份应用程序数据库并存储在移动存储中
文件夹。 我尝试这样做,但无法创建备份文件。
try{
File data = Environment.getDataDirectory();
File sd = new File(Environment.getExternalStorageDirectory()+"/digiplusBackUp");
if(!sd.exists()){
sd.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df1 = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate1 = df1.format(c.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
String formattedDate3 = dateFormat.format(c.getTime());
if (sd.canWrite()) {
String currentDBPath = "//data//com.digiplus.live//databases//digiplus";
String backupDBPath = "DigiPlus"+formattedDate1+formattedDate3 ;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
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 ignored) {
Log.d("Error",ignored.tostring());
}
}
【问题讨论】:
-
您是否设置了清单以允许写入外部存储?如果 Android 是 M 或更高版本,您是否请求过许可。您收到什么错误消息?您应该编辑您的问题以包含堆栈跟踪(不要忽略捕获打印中的异常,以便您可以获取堆栈跟踪)。
-
我维护清单上的所有权限。
-
编辑后忽略大小写使用 e 并给我这个错误 /Error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.parse.ParsePlugins.applicationContext()'在空对象引用上
-
尝试将
Toast.makeText(getApplicationContext(), "Backup is successful to SD card", Toast.LENGTH_SHORT).show();替换为Log.d("BACKUP-RESULT","backup to SD card was ok");。getApplicationContext的赔率返回 null;理想情况下在 catch 子句中添加ignored.printStackTrace();,如果上述方法不能解决问题(比输出字符串进行调试要好得多)。
标签: android sqlite database-backups dbflow