android getCacheDir() 处的 NullPointerException

use*_*706 3 java singleton android nullpointerexception

我正在尝试以编程方式清除我的应用程序数据。但我得到了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();
}
Run Code Online (Sandbox Code Playgroud)

}

我有一段NullPointerException时间尝试做:-

File cache = getCacheDir();
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

dug*_*ggu 5

尝试下面的代码:-

File cache = getApplicationContext().getCacheDir();
Run Code Online (Sandbox Code Playgroud)

发生此错误是因为getCacheDir()函数需要应用程序的上下文。