PPD PPD - 4 months ago 46
Android Question

Nullpointer exception in android API level 21

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();


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


Any suggestion will be appreciated. Thanks in advance.

Answer

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();

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

You are calling getPath() twice without checking for null.

Try this:

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();
    }
}