我正在尝试以编程方式清除我的应用程序数据。但是我得到了一个带有以下代码的 NullPointerEXception
。
这是我的代码:-
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance(){
return instance;
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if(appDir.exists()){
String[] children = appDir.list();
for(String s : children){
if(!s.equals("lib")){
deleteDir(new File(appDir, s));
Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s +" DELETED *******************");
}
}
}
}
public 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();
}
我在尝试执行时遇到了 NullPointerException
:-
File cache = getCacheDir();
我该如何解决?
最佳答案
试试下面的代码:-
File cache = getApplicationContext().getCacheDir();
发生此错误是因为 getCacheDir()
函数需要应用程序上下文。
关于java - getCacheDir() android 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360417/