user4757345 user4757345 - 2 months ago 20
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);
folder.mkdir();


mkdir always return false. I added permission to manifest file

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


I can create folder with
adb
tool.

Phone is Nexus 5 Android 6.0.1

what is wrong with code ?

Answer

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

 ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);

And add this method (optional):

@Override
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();
            }
            return;
        }
    }
}
Comments