mremremre1
mremremre1

Reputation: 1036

Can't create a folder in external storage, Android

I tried a lot to find a solution but everything has failed so far. It's probably something stupid.

I'm trying to save a photo as a jpeg in the storage of the phone. Everything fails even the simple task of making a folder. The code below is what I use to create the folder.

private void makeFolder(){
    try{
        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),getString(R.string.app_name));
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            Toast.makeText(this,"Done",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,"folder_failed",Toast.LENGTH_SHORT).show();
            System.out.println(folder.getAbsolutePath());
        }
    }catch (Exception e){
        Toast.makeText(this,"exception",Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

I have tried many different ways like:

        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                File.separator + getString(R.string.app_name)+File.separator);

        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                File.separator + getString(R.string.app_name);
        
        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                ,getString(R.string.app_name));

I have tried both mkdirs and mkdir and

-Environment.getExternalStorageDirectory().getAbsolutePath()
-getExternalStorageDirectory().getAbsolutePath()
-Environment.getExternalStorageDirectory()
-getExternalStorageDirectory()

The permission exists in the manifest and is accepted.

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

The path the the System.out prints is "/storage/emulated/0/appname"

I don't know what else to try. Similar code works for other applications. Min API is 23. Any help is much appreciated.

Upvotes: 0

Views: 953

Answers (2)

Felix
Felix

Reputation: 292

If your test device runs Android 10/Q or API Level 29+: there are a few permission changes with storing data to media folder. You can store your data without problems to your app folder, but if you remove the app the images are gone too.

The easiest way is to add android:requestLegacyExternalStorage="true" in the manifest under application but it is more like a work around and it will probably not be supported for long.

Search for "store image android 10" here and you find the right way for you.

Upvotes: 1

Steyrix
Steyrix

Reputation: 3226

I suggest you to try Context.getExternalFilesDir() instead of Environment.getExternalStorageDirectory()

Upvotes: 1

Related Questions