1

I'm trying to create a folder in the internal storage of the device where the user can access the data (don't wanna do the folder here: /data/data/package.name/app_MyDirName).

After a lot of researching, i have that but there's always an error creating the file:

    public void createFolder(View v){
        File folder = new File(Environment.getDataDirectory() + File.separator + "YOUR_FOLDER_NAME_HERE");
        if (!folder.exists()) {
            if(folder.mkdirs()){
                Log.d("App","file created successfully");
            }else{
                Log.d("App","error creating folder");
            }
        }else{
            Log.d("App","folder exists");
        }
    }

I've been trying to solve this for a while so I would be really thankful if someone could help me!

Samuel
  • 53
  • 6
  • 1
    Welcome to stackoverflow. To be more clear on your question, could you please attach the error that you are getting when trying to create the folder ? and may be share a stack trace as well ? – Damith Dec 26 '20 at 12:31
  • Related question: https://stackoverflow.com/questions/64720379/writing-many-files-on-android-11 – Robert Dec 26 '20 at 15:18

1 Answers1

0

Try this....just replace your function

    public void createFolder(View v){
    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "YOUR_FOLDER_NAME_HERE");
    if (!folder.exists()) {
        if(folder.mkdirs()){
            Log.d("App","file created successfully");
        }else{
            Log.d("App","error creating app");
        }
    }else{
        Log.d("App","folder exists");
    }
}

And make sure if your target and compilesdk is 29 or above, you must add " android:requestLegacyExternalStorage="true" in your manifest file.

Hope this will work.

pratik vekariya
  • 1,105
  • 1
  • 8
  • 14
  • The `android:requestLegacyExternalStorage` workaround does not work on native Android 11+ devices. Therefore it is a bad idea to present code that fails on a growing number of devices. – Robert Dec 26 '20 at 15:16
  • @Robert, Android 11 devices dont need that workaround as folders can be created everywhere except for root of external storage. So in all public directories that are already there. – blackapps Dec 26 '20 at 19:21