Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

final File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
for (final String fileEntry : folder.list()) {
 System.out.println(fileEntry);
}

Environment.getExternalStorageState() this will give you state of External storage not Path. For checking path please use Environment.getExternalStorageDirectory().getAbsolutePath().

And as per your mentioned sate "shared" it seems you were testing while you accessing it via USB cable into your System. Because "shared" state means "media is present not mounted, and shared via USB mass storage".

Try getting path to external storage through this:

  System.out.println(Environment.getExternalStorageState());

which returns the path to external storage and cross check it with what you are writing.

Can you try this code

final File folder = new File("/storage/sdcard");

    if (folder.getAbsoluteFile().exists()) {
        for (final String fileEntry : folder.getAbsoluteFile().list()) {
            System.out.println(fileEntry);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top