Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create directory on Android 6.0 with mkdirs (storage permission ok)

I'm trying to update my app source code to Android 6.0 with the new runtime permissions.

But also if the user grants to app the storage permission, the app is not able to create directories in the 'onRequestPermissionsResult' method using the 'mkdirs'.

In the AndroidManifest.xml I put the 'uses-permission':

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xample.provasd"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="23" />

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

    <!-- application, activity, etc -->

Then in the MainActivity I deal with the permission request:

public void executeButton(View view){
        final String[] PERMISSIONS_STORAGE = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
        //Asking request Permissions 
        ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE, 9);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean writeAccepted = false;
        switch(requestCode){
        case 9:
            writeAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
            break;
        }
        if(writeAccepted){
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File dir = new File(Environment.getExternalStorageDirectory()+"/"+"TestFolder");
                boolean b = dir.mkdirs();
                if(b){
                    Log.i("TAG", "WOW! "+dir+" created!");
                }else{
                    Log.e("TAG", "OPS! "+dir+" NOT created! To be sure: new dir exist? "+dir.exists());
                }
            }
        }       
    }

Launching the app on emulator, the request dialog is showed: allowing the permission the body of 'onRequestPermissionsResult' is executed (writeAccepted=true) BUT the folder is not created!

This is what appear in the LogCat:

I/TAG(9020): Permission ok
I/TAG(9020): Try to create dir: /storage/3143-1CEA/TestFolder
E/TAG(9020): OPS! /storage/3143-1CEA/TestFolder NOT created! To be sure: new dir exist? false

I don't understand the reason.

Please, someone can help me?

Thank you,

Mirko

like image 286
Mirko Avatar asked Nov 09 '22 20:11

Mirko


1 Answers

The problem may not lie in the code. If your phone is running on Android 6.0, look to see if your App has sufficient permissions.

like image 141
chaosxing Avatar answered Nov 14 '22 21:11

chaosxing