Search code examples
javaandroiddirectoryandroid-sdcard

Android create directory


I'm trying to create a folder in the Downloads directory on the SDcard of an Android device. I have declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the manifest.

Here's my code:

String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        Log.e("file writer", "Directory not writeable");
        Toast.makeText(this, "Not writeable.",
                Toast.LENGTH_SHORT).show();
    }

    File dir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "myfolder");
    dir.mkdirs();
    if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); }

I get the "directory not created" error and there's obviously no folder where I intend there to be one.


Solution

  • for getting permission in Android 6+ you should ask user, try this

            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
            }
        }