Tuesday, February 17, 2015

Android : File exists but canRead() returns false

I'm working my way through this developer document about capturing and saving photos and ran into a problem. My photo was saved properly, I could call up the ADB shell and verify it. But when I tried to read it back so that I could display it on the screen, this code would fail:

File imgFile = new  File(mCurrentPhotoPath);
if(imgFile.exists()) {
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    ImageButton btn = (ImageButton)findViewById(R.id.photoButton);

Sound familiar? I had requested the WRITE_EXTERNAL_STORAGE permission properly (which implicitly gets the READ_EXTERNAL_STORAGE permission as well), so that wasn't the problem.

It turns out that the file does indeed exist, but it was failing on canRead().  Since canRead()==false, exists() was also returning false.

Ok, then, why can't I read it?

The problem lies in the photoPath, and whether to use a URI or a regular file path descriptor.  The code that we're talking about ends up structuring a unique image filename that looks like this:


which worked fine to save the file. But on a hunch I tried a pure file path:


and guess what? That worked.