gpt4 book ai didi

java - getCacheDir() android 中的 NullPointerException

转载 作者:太空狗 更新时间:2023-10-29 16:17:08 24 4
gpt4 key购买 nike

我正在尝试以编程方式清除我的应用程序数据。但是我得到了一个带有以下代码的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com