androidfilenosuchfileexception

Android says no such file or folder even though it's there


I'm trying to access files inside my Android phone, and the code below is used for it:

final File folder = new File("/storage/sdcard0/");
        for (final String fileEntry : folder.list()) {
            System.out.println(fileEntry);
        }

It throws a null pointer on list() function, meaning it's not a file/directory. However, if I change the path to /storage/, it prints a bunch of folders including sdcard0. I know sdcard0 actually is a folder/file because I also downloaded a file manager for my phone and went through the files. Many people suggest using getExternalStorageDirectory(), but that results in the same null pointer.

I have added these permissions:

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

EDIT: one of the many sites that I've looked at android null pointer error

UPDATE: I checked if it was a folder using isDirectory(), and it returns true, then I tried canRead() and it returns false, maybe it's a permission issue?


Solution

  • FINALLY I figured it out, if you slide the top menu bar (where you receive notifications) there's "Connected as a media device", if you click that there is more settings, and if you enable "Media device (MTP)", not having this set was automatically unmounting my sdcard when I plugged it in via USB to my computer.