Android getExternalCacheDir() returns null

FoamyGuy picture FoamyGuy · Jan 18, 2013 · Viewed 9.1k times · Source

I am trying to implement the best practices described in Loading Bitmaps effeciently

I've run into trouble because this line:

Utils.getExternalCacheDir(context)

inside of DiskLruCache.java is returning null, which means I get NullPointerException when I try to call .getPath()

Answer

FoamyGuy picture FoamyGuy · Jan 18, 2013

Despite the somewhat cryptic NullPointerException that gets thrown the actual issues is that my application did not have WRITE_EXTERNAL permission, so the system was rejecting my attempt to use the ExternalDir for caching. Unfortunately this was happening at a low enough level in the code used in Displaying Bitmaps Effeciently that the Exception does not indicate SecurityException as it normally would if one were trying to write to the SD card without the proper permission.

To fix simply add this:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

to your manifest.