我正在尝试为我的应用程序创建重置应用功能,并且我尝试从内部存储中删除所有文件,包括files folder
,databases folder
和shared preferences
。问题是,每当我尝试删除这些文件夹时,都不会删除它们。有时我用来删除文件的函数返回false。在这种情况下,我的应用程序无法正常工作。这是我正在使用的:
@SuppressWarnings("static-access")
public void deleteAllData(){
String cache = this.getCacheDir().toString();
Log.e("","dbPath : "+cache);
File ChFolder = new File(cache);
boolean cachee = deleteDirectory(ChFolder);
Log.e("","Database Folder Delete Success : "+cachee);
String server = rpc.getCurrentServerName(this);
int userId = rpc.getUserId(this);
String userDbPath = "/data/data/"+this.getPackageName()+"/databases/"+Integer.toString(userId)+"_"+server;
File userDbFile = new File(userDbPath);
boolean userDbFileTF = userDbFile.delete();
Log.e("","user Database Folder : "+userDbFileTF);
String sysDbPath = "/data/data/"+this.getPackageName()+"/databases/stampii_sys_tpl.sqlite";
File sysDbFile = new File(sysDbPath);
boolean sysDbFileTF = sysDbFile.delete();
Log.e("","user Database Folder : "+sysDbFileTF);
// Delete Databases Folder :
String dbPath = "/data/data/"+this.getPackageName()+"/databases/";
Log.e("","dbPath : "+dbPath);
File dbFolder = new File(dbPath);
boolean dbFold = deleteDirectory(dbFolder);
Log.e("","Database Folder Delete Success : "+dbFold);
// Delete Files Folder :
String name = this.getFilesDir().toString()+"/users/";
Log.e("","path : "+name);
File files = new File(name);
boolean filesFol = deleteDirectory(files);
Log.e("","filesFol : "+filesFol);
}
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}
我是否缺少某些内容,如何在Android设置中实现Clear Data
之类的功能,这也会删除数据库。
答案 0 :(得分:2)
使用以下代码。它应该自动删除所有数据。在继续执行此操作之前,请确保没有正在使用的数据库/文件或任何缓存资源:
/**
* Call this method to delete any cache created by app
* @param context context for your application
*/
public static void clearApplicationData(Context context) {
Log.i("delete", "Clearing app cache");
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
File f = new File(appDir, s);
if(deleteDir(f))
Log.i("delete", String.format("*** DELETED -> (%s) ***",
f.getAbsolutePath()));
}
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
答案 1 :(得分:1)
目录必须为空才能删除。以下是如何从目录中删除文件然后删除目录本身的示例。