在Android的API级别21空指针例外

在Android的API级别21空指针例外

本文介绍了在Android的API级别21空指针例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家在我的应用我使用以下code:

Hi all In my application I am using following code:

 final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
            !Environment.isExternalStorageRemovable() ? getExternalCacheDir(context).getPath()
            : context.getCacheDir().getPath();

在上面Android版本pre棒棒糖code运行正常,但在API级别21我正在dollowing误差:

Above code run fine on android version pre lolipop, But on API level 21 I am getting dollowing error as:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getPath()' on a null object reference

任何建议将AP preciated。谢谢advace

Any suggestion will be appreciated. Thanks in advace

推荐答案

看code你贴,你自己做你的权利是:

Look at the code you posted, did you right this yourself?:

final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
            !Environment.isExternalStorageRemovable() ? getExternalCacheDir(context).getPath()
            : context.getCacheDir().getPath();

您在Android中,得到了最常见的错误 NullPointerException异常

You got the most common error in Android, a NullPointerException:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getPath()' on a null object reference

您在呼唤的getPath()不检查两次。

试试这个:

String cachePath; // you still need a default value if not mounted

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
    if (getExternalCacheDir(context) != null) {
        cachePath = getExternalCacheDir(context).getPath(); // most likely your null value
    }
} else {
    if (context.getCacheDir() != null) {
        cachePath = context.getCacheDir().getPath();
    }
}

这篇关于在Android的API级别21空指针例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:47