5

So the problem I have is the following,

the following line of code throws a NullPointerException for some users of my app, yet i don`t know why

String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
    baseDir = getExternalFilesDir(null).getAbsolutePath();
else
    baseDir = getFilesDir().getAbsolutePath();

to be more specific its this part

baseDir = getExternalFilesDir(null).getAbsolutePath();

This code is called in the OnPostCreate() and I also have the required permissions in case you wondered.

So getExternalFilesDir(null) returns null for some reason even though it would be mounted.

I also searched a bit on SO and found related post with the same question but no real answer only good one is this one.

So is this just a problem on some user phones or a problem in general on androids end ?

1 Answer 1

6

This is strange. The android documentation says it only returns null when the external storage is not mounted. I think the right thing to is this:

String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
    File baseDirFile = getExternalFilesDir(null);
    if(baseDirFile == null) {
        baseDir = getFilesDir().getAbsolutePath();
    } else {
        baseDir = baseDirFile.getAbsolutePath();
    }
} else {
    baseDir = getFilesDir().getAbsolutePath();
}
Sign up to request clarification or add additional context in comments.

2 Comments

hmmm, yeah it pretty much the only solution to this I assume. Yet it would be interessting to know why this can happen. My only assumption would be that it depends on the implementation of the manufacture.
I've seen this problem as well, but for me, it's sporadic and does not depend on the user. I think it's a timing problem within the OS, but I haven't been able to make it happen, so I can't submit a bug report.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.