Java – Why does getExternalStorageDirectory return my phone’s root storage instead of the SD card?

Why does getExternalStorageDirectory return my phone’s root storage instead of the SD card?… here is a solution to the problem.

Why does getExternalStorageDirectory return my phone’s root storage instead of the SD card?

I’m trying to read data from a folder on my phone’s SD card with path \weights\input. Android’s Environment.getExternalStorageDirectory().toString() returns /storage/emulated/0, and isDirectory() for that path returns true. But when I execute the code below:

File weights = Environment.getExternalStorageDirectory();
List<File> inputs = getListFiles(weights);

The inputs list contains all the files in my phone’s internal memory, not the SD card, so when I look up directories in inputs, my app fails.

Why is that? By the way, I’m completely new to Android and Java. Completely.

Solution

I’m having a similar issue, I tried appending / at the end. You can try the following:

/weights/input/

Replace

/weights/input

Edit:
After editing, I found this :

getExternalStorageDirectory is implemented to return whatever is set
as “external storage” in the device environment:

public static File getExternalStorageDirectory() {
    return EXTERNAL_STORAGE_DIRECTORY;
}

and EXTERNAL_STORAGE_DIRECTORY is:

private static final File EXTERNAL_STORAGE_DIRECTORY = getDirectory("EXTERNAL_STORAGE", "/sdcard");

static File getDirectory(String variableName, String defaultPath) {
    String path = System.getenv(variableName);
    return path == null ? new File(defaultPath) : new File(path);
}

In contrast, getExternalStoragePublicDirectory(String type) requires
one of these strings:

DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES,
DIRECTORY_MOVIES, DIRECTORY_DOWNLOADS, or DIRECTORY_DCIM. May not be
null.

So it’s not about returning sd roots.

Alternatives:

Finally, getExternalStorageState() returns the file system
Mount at /mnt/sdcard/. According to CommonsWare in this answer:
Find an external SD card location, there is no way to be direct
Get an external SD card, if it is present.

Another approach is to check isExternalStorageRemovable () and
Give a manual option if it is fake.

Source: This link.

Related Problems and Solutions