ProgFroz
ProgFroz

Reputation: 367

Can't create directory with mkdirs() - android

I try to create a directory and use the following code:

boolean success = true;
String rootDirectory = Environment.getExternalStorageDirectory().toString();
folder = new File(rootDirectory, "Directory");
if(!(folder.exists())) {
     success = folder.mkdirs();
} else {

}

if(success) {
   Toast.makeText(getActivity().getApplicationContext(), "DIR created", Toast.LENGTH_SHORT).show();     
} else {
     Toast.makeText(getActivity().getApplicationContext(), "DIR not created successfully", Toast.LENGTH_SHORT).show();
}

I also searched for the folder if it was created, there is none.

Permissions are granted:

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

I also tried to ask for permission during runtime, it seems like the app has got the permission, therefore it cannot be the problem.

Some months ago I created another application and used identical code and the identical Sdk version, still it does not work with this one. I get "DIR not created successfully" and I do not know why, please help me figure out why I cannot create the directory.

Upvotes: 3

Views: 9229

Answers (4)

Wowo Ot
Wowo Ot

Reputation: 1529

In the new Android update API 30 you can only write in your app local files app-specific files

File dir = new File(context.getFilesDir(), "YOUR_DIR");
dir.mkdirs();

or in the external storage of your app Android/data

final File dir = new File(myContext.getExternalFilesDir("FolderName"),"YOUR_DIR");

UPDATE

this answer provided another solution https://stackoverflow.com/a/65744517/8195076

UPDATE

another way is to grant this permission in manifest

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

like this answer https://stackoverflow.com/a/66968986/8195076

Upvotes: 2

xbadal
xbadal

Reputation: 1375

String path = Environment.getExternalStorageDirectory().toString() + "/" +"MyDir";
File dir = new File(path);
if(!dir.exists())
{
    dir.mkdirs()
}

Upvotes: 0

Jarda Pavl&#237;ček
Jarda Pavl&#237;ček

Reputation: 1846

Asking for Manifest.permission.WRITE_EXTERNAL_STORAGE is no more sufficient for Android 10+. Now you have also enable access to legacy external storage in manifest:

<application
    android:requestLegacyExternalStorage="true"
    ...

Upvotes: 5

Haris Qurashi
Haris Qurashi

Reputation: 2124

Use code below

File directory = new File(Environment.getExternalStorageDirectory() + java.io.File.separator +"Directory");
if (!directory.exists())
        Toast.makeText(getActivity(), 
          (directory.mkdirs() ? "Directory has been created" : "Directory not created"),
        Toast.LENGTH_SHORT).show(); 
else
     Toast.makeText(getActivity(), "Directory exists", Toast.LENGTH_SHORT).show();

For Android API 23 (Marshmallow) and greater, we have to allow dangerous permissions otherwise our code will not work as we expected.

Upvotes: 0

Related Questions