我的应用程序将其数据库存储在SD卡上
DatabaseHandler类
private static final String DATABASE_NAME = "MyDb";
private static final String KEY_ROOT_FOLDER= Environment.getExternalStorageDirectory().getAbsolutePath() + "/.MYAPP/" + DATABASE_NAME;
public DatabaseHandler(Context context) {
Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+ FOLDER_NAME+File.separator, null, DATABASE_VERSION);
super(context, KEY_ROOT_FOLDER, null, DATABASE_VERSION);
}
因此,当用户卸载应用程序时,我的数据库不会删除(因为它存储在ExternalStorageDirectory下)。我想在用户再次安装应用程序时创建数据库的新副本。
因此我首先在应用程序上运行并使用此代码删除以前的数据库。
public void checkReinstallApp(){
SharedPreferences settings = getSharedPreferences("FIRSTRUN", 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if (firstRun) {
Log.w("activity", "first time");
isFirstTime=true;
if(permissionHelper.isPermissionGranted( Manifest.permission.READ_EXTERNAL_STORAGE)){ //for getting permission Android 6
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.commit(); // Save all changed settings
try{
WebViewActivity.this.deleteDatabase(SET_START_DIRECTORY+"MyDb");
}catch (Exception e){
// Error
}
File f = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/.MYAPP/");
deleteFile(f);
}else{
permissionHelper.setForceAccepting(true).request(PERMISSION);
}
} else {
Log.w("activity", "second time");
}
}
我在
上调用checkReinstallApp()方法的onCreate
但是,当我卸载应用程序并重新安装它时,它显示没有错误。但是数据库没有被删除。请为此提出解决方案。
PS-I尝试使用此代码删除包含DB文件和其他文件的文件夹。
File f = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/.MYAPP/");
deleteFile(f);
public boolean deleteFile(File file) {
if(permissionHelper.isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteFile(new File(file, children[i]));
if (!success) {
return false;
}
}
}
return file.delete();
}
}else {
permissionHelper.setForceAccepting(true).request(PERMISSION);
deleteFile( file);
}
return false;
}
然后它显示此警告消息
:android.system.ErrnoException:chmod失败:EPERM(不允许操作)
答案 0 :(得分:0)
可能是你在使用android 6.0。所以你必须考虑运行时权限。
即时解决方案:将gradle中的targetSdkVersion更改为22.不推荐但有效。