1

I am trying to create a new folder inside sdcard using context.getExternalFilesDir() method but it doesn't work, it creates Pictures folder but it doesn't create TestFolder and txt file. My intention is to create a folder and put downloaded images from my app inside it. Unfortunately, Environment.getExternalStorageDirectory() is deprecated in API level 29 and I don't know how to fix it. As always, thank you a lot for your help!

        File folder = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "TestFolder");
        if (!folder.exists()) {
            folder.mkdirs();
        }


        File filename = new File(folder, "test.txt");
        try {
            filename.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
  • Note that the code in your question does not show the use of `Environment.getExternalStorageDirectory()`. It shows `getExternalFilesDir()`, which works well on Android 4.4 through 10 (and, so far, on Android R). So, the title of your question does not really match the body of the question. Beyond that, look at Logcat to see if you are getting a stack trace from an exception. Bear in mind that `createNewFile()` does not really do much and is not really used in Android app development. – CommonsWare Apr 18 '20 at 19:41
  • Hello. Now the title is better for you? Thank you for your suggestion about createNewFile. I don't get any errors in my terminal. – Samuele Calugi Apr 18 '20 at 19:53
  • "it creates Pictures folder but it doesn't create TestFolder and txt file" -- how exactly are you looking for it? Try using Device File Explorer in Android Studio. – CommonsWare Apr 18 '20 at 19:55
  • Device File Explorer shows all my files and folders that I have tried to create before, thank you. But why I can't see them in my android emulator? I need to get access to these files. Thank you again – Samuele Calugi Apr 18 '20 at 20:03
  • If you are looking for these images in a gallery-style app, `getExternalFilesDir()` does not get indexed by the `MediaStore` on Android 10+. IIRC, it *can't* be indexed by `MediaStore`. If you want to write out images, particularly to standard public locations on external storage, you might consider working with `MediaStore` directly. I have a bunch of blog posts on it, starting [here](https://commonsware.com/blog/2019/12/21/scoped-storage-stories-storing-mediastore.html). – CommonsWare Apr 18 '20 at 20:23
  • Thank you a lot! – Samuele Calugi Apr 18 '20 at 20:40

1 Answers1

0

use

File folder = new File(this.getExternalFilesDir(null).getAbsolutePath(), "TestFolder");

instead of

File folder = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "TestFolder");

Abhi
  • 1,043
  • 12
  • 7