Search code examples
javaandroiddirectoryandroid-file

Unable to create a folder(directory) in Android 11, how to create it?


I am unable to create a folder in my Android 11 device using java. I used this piece of code

 File file = new File(Environment.getExternalStorageDirectory() + "/folderName/folderName1");
        if (!file.mkdirs()) {
            file.mkdirs();
        }
String filePath = file.getAbsolutePath() + File.separator + "demoName";
        Log.i("filePath",filePath.toString());

The output of above log statement is /storage/emulated/0/folderName/folderName1/demoName but when I check my phone there is no such folder created.

Just to confirm I have researched and did include everything I need to include in the Manifest file.

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

And I have also placed

 android:requestLegacyExternalStorage="true"

in the correct place inside of the application tag.

This is what I do to download a PDF from a link.

 File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/Aide Memoire");

    public  void DownloadBooks(String url,String title){

        DownloadManager.Request request=new DownloadManager.Request(Uri.parse(url));
        String tempTitle=title.trim();
        request.setTitle(tempTitle);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB){
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        String filePath = file.getAbsolutePath();
        Log.i("filePath",filePath.toString());
        request.setDestinationInExternalPublicDir(filePath,tempTitle+".pdf");
        Toast.makeText(this, "Saved to " + filePath , Toast.LENGTH_SHORT).show();
        DownloadManager downloadManager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
        request.setMimeType("application/pdf");
        request.allowScanningByMediaScanner();
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        downloadManager.enqueue(request);
    }
DownloadBooks("a link"," a name for the file");

After running the above I get an error and the logcat says

java.lang.IllegalStateException: Not one of standard directories: 

Now, how do I create a custom folder in Internal Storage in Android 11 without error ?


Solution

  • Well thats called external storage as you can see on that function name.

    But on an Android 11 device you cannot create your own subdirectories on root of external storage.

    Instead do it on one of the public directories that are already there like Documents, DCIM, Pictures and so on