Creating a directory in /sdcard fails

Viewed 109864

I have been trying to create a directory in /sdcard programmatically, but it's not working. The code below always outputs directory not created.

boolean success = (new File("/sdcard/map")).mkdir(); 
if (!success) {
    Log.i("directory not created", "directory not created");
} else {
    Log.i("directory created", "directory created");
}
13 Answers

There are Many Things You Need to worry about 1.If you are using Android Bellow Marshmallow then you have to set permesions in Manifest File. 2. If you are using later Version of Android means from Marshmallow to Oreo now Either you have to go to the App Info and Set there manually App permission for Storage. if you want to Set it at Run Time you can do that by below code

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}

If the error happens with Android 6.0 and API >=23 ; Giving permission in the AndroidManifest.xml is not alone enough.

You have to give runtime permissions, you can refer more here Runtime Permission

                       (or)

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:

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

    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true">
     ...
     ...
    </application>
</manifest>

You can read more about it here: https://developer.android.com/training/data-storage/compatibility


Internal Storage vs Seconday Storage

The internal storage is referred to as "external storage" in the API ; not the "secondary storage"

Environment.getExternalStorageDirectory();

As mentioned in the Environment Documentation

Related