java - getCacheDir() android 中的 NullPointerException

标签 java android nullpointerexception singleton

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

相关文章:

java - ResponseEntity 无法解析为类型

android - 覆盖图像 mask 不适用于 Motorola Xoom (android 4.0.4)

android - 值等于dimens.xml 中的match_parent 和fill_parent?

Android 中的 java.lang.nullpointer 错误

java - 什么是 NullPointerException,我该如何解决?

java - AsynchCallback 上的空指针异常

java - 获取辅助监视器的位置。 (小学的右侧或/左侧)

java - 每 5 小时创建一个表

java - 为什么 java.util.Properties 实现 Map<Object,Object> 而不是 Map<String,String>

java - Android:如何不保存实例状态?