1

I am trying to write something to the ExternalStorageDirectory on my Android device. To test this, I tried to create a simple folder in this directory. As it has not been working I stumbled across this stackoverflow thread. When I use the most upvoted example code

File folder = new File(Environment.getExternalStorageDirectory() + "/map");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

and set the givven WRITE_EXTERNAL_STORAGE permission, the creation of the folder is always failing - there is no exception, but after the execution f.exists() is still false. I tested this on my Nexus 5X and the latest Nexus 5X-Emulator.

In the emulator Environment.getExternalStorageState() returns not-mounted although I mounted the virtual SD-card (this seems also strange to me). In my physical device it returns mounted - so I do not see any problem, why the code should not be working.

Any advices for the solution of the failure of the creation of the folder and/or the behaviour of the Environment.getExternalStorageState() are welcome.

Community
  • 1
  • 1
zimmerrol
  • 4,872
  • 3
  • 22
  • 41

1 Answers1

0

Make sure to add this permission into manifiest file

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

and create folder like this

String folder_main = "map";

File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
    f.mkdirs();
}
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60