android – getExternalFilesDir() returns null (not a permissions issue)-ThrowExceptions

Exception or error:

I’ve been working on an app for some time, and have been testing it on many devices. Suddenly, it stopped working on the Motorola Xoom Family Edition (Honeycomb 3.1). Every time I would try to run the app, it would fail on the call to getExternalFilesDir(), as that call would return null instead of a File.

From my research, anyone with a similar problem is either missing the WRITE_EXTERNAL_STORAGE, never got an answer, or was talking about a bug in Froyo. None of that applies here–and again, it works fine on other devices, I have the WRITE_EXTERNAL_STORAGE permission, and it was even working on this device until a few minutes ago.

Any idea what might cause this issue, or how to programmatically prevent it?

How to solve:

The problem went away after I restarted the tablet. It may just be some bizarre quirk that is extremely rare and fixed by a simple restart; I hope not, as I would like to have a solid way to prevent this instead of just hoping that any users who run into the bug are understanding.

###

Same problem on Samsung SCH-1405 (VZW Galaxy II) running 2.3.6 (kernel 2.6.35.7-FF1). No problems getting the external files directory for months and then bam, it starts to return NULL. Restarted phone and problem went away. Not a good omen.

A possible cause could be that I’ve been switching this phone in and out of USB debugging mode to get screen shots and have been ripping out the USB cable from the phone without first unmounting the phone’s file systems from my Mac. This is new behavior on my part.

When I look at the return result from android.os.Environment.getExternalStorageState() with the problem present I see “shared”, but when the phone is restarted the result is “mounted”. Thus it seems that when the phone thinks that the external storage is “shared” then it is not allowing an app to access the external storage. This is speculation.

###

This will happen if the device is in “Mass Storage” mode. If you change it to MTP or “Charge Only”, depending on the device, it should work. This is because the external data storage is technically not mounted to the device but to your computer.

Leave a Reply

Your email address will not be published. Required fields are marked *