skaldesh
skaldesh

Reputation: 1530

Android: Retrieve all image directories

I am trying to find all directories on an Android device that contain images (internal as well as external storage).
Basically, I try to get all the directories that are listed in the native gallery application

So for example:

How does one accomplish this? I think it is related to MediaStorage.Images.Media and so on, but the documentation is not very helpful there and a lot of google searches didn't help as well.

Upvotes: 3

Views: 7250

Answers (2)

FadedCoder
FadedCoder

Reputation: 1517

You can use this code to find picture folders in Storage -

private ArrayList<File> fileList = new ArrayList<File>();    

...

public ArrayList<File> getfile(File dir) {
    File listFile[] = dir.listFiles();
    if (listFile != null && listFile.length > 0) {
    for (int i = 0; i < listFile.length; i++) {
        if (listFile[i].getName().endsWith(".png")
                || listFile[i].getName().endsWith(".jpg")
                || listFile[i].getName().endsWith(".jpeg")
                || listFile[i].getName().endsWith(".gif"))
            {
                String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
                fileList.add(temp);
            }
        }
    }
    return fileList;
}

And then you can call the ArrayList this way -

File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
getFile(root);
for (int i = 0; i < fileList.size(); i++) {
    String stringFile = fileList.get(i).getName();
    Do whatever you want to do with each filename here...
}

Upvotes: 5

skaldesh
skaldesh

Reputation: 1530

Thanks to @BlazingFire, who did not fully answer my question, but provided some code I could work with and have now my desired result:

public ArrayList<String> getFile(File dir) {
    File listFile[] = dir.listFiles();
    if (listFile != null && listFile.length > 0) {
        for (File file : listFile) {
            if (file.isDirectory()) {
                getFile(file);
            }
            else {
                if (file.getName().endsWith(".png")
                        || file.getName().endsWith(".jpg")
                        || file.getName().endsWith(".jpeg")
                        || file.getName().endsWith(".gif")
                        || file.getName().endsWith(".bmp")
                        || file.getName().endsWith(".webp"))
                {
                    String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
                    if (!fileList.contains(temp))
                        fileList.add(temp);
                }
            }
        }
    }
    return fileList;
}

It only adds parent directories of images and only if they have not yet been added. I also included .bmp and .webp as valid image file extensions

Upvotes: 6

Related Questions