user4757345 user4757345 - 1 year ago 99
Android Question

mkdir() fails with SD card although there is permission

I try to create a folder in sdcard

File folder = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "folder");
Log.d(TAG, "FOLDER :" +folder);

mkdir always return false. I added permission to manifest file

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

I can create folder with

Phone is Nexus 5 Android 6.0.1

what is wrong with code ?

Answer Source

In android 6.0+ you have to request permission at runtime, so in onCreate() request WRITE_EXTERNAL_STORAGE

                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},

And add this method (optional):

public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
          if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted!        
            } else {

                // permission denied!
                Toast.makeText(MainActivity.this, "Permission denied to write External storage", Toast.LENGTH_SHORT).show();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download