androidandroid-studioandroid-6.0-marshmallowmkdirs

File.mkdirs() does not create the folders - Android Marshmallow (API 23)


Android Manifest Permissions

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

Java file (First try)

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newAppFolder";
File dir = new File(path);
dir.mkdirs();

Java file (Second try)

String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
    File dir = new File(Environment.getExternalStorageDirectory(), "newAppFolder");
    if(!dir.exists()) {
        dir.mkdirs();
        Toast.makeText(getApplicationContext(), "Folder Created", Toast.LENGTH_LONG).show();
    }
    else
        Toast.makeText(getApplicationContext(), "Folder exists", Toast.LENGTH_LONG).show();
    }

else
    Toast.makeText(getApplicationContext(), "SD Card Not Found", Toast.LENGTH_LONG).show();

Unfortunately neither attempt creates the newAppFolder file that I need. Can someone please tell me what I'm doing wrong?

Note: In the second try, the application toast keeps showing Folder Created


Solution

  • Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

    If your target sdk is 23, you should check this link and see if requesting permission at runtime fixes it.