M
M
Michael Kim2016-11-27 01:23:34
Java
Michael Kim, 2016-11-27 01:23:34

How to select only one image from a folder?

I am writing a gallery for the application. Here, with the help of this function, I recursively go through all the directories and look for pictures there

private ArrayList<Album> getAlbums(File root){
        ArrayList<Album> albums = new ArrayList<>();
        String androidDataFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data";
        File[] fileList = root.listFiles();
        String exts = "jpg png jpeg";
        String file_ext;

        for(File f: fileList){
            if(f.isDirectory() && !f.isHidden()
                    && !f.getAbsolutePath().equals(androidDataFolder)) {
                    albums.addAll(getAlbums(f));
            }
            else {
                file_ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
                if(exts.contains(file_ext)) {
                    albums.add(new Album(f.getParent(), f));
                }
            }
        }
        return albums;
    }

Everything works, it finds all the pictures, but I want to sort the pictures by albums, that is, in fact, display only the first picture from the folder on the screen. That is, I do not need to search for all the photos in a specific folder. How to make sure that there are no several pictures from the same folder? Of course, you can get a list with all the pictures and then clean up the duplicates with this function
private ArrayList<Album> clearAlbums(ArrayList<Album> albums){
        boolean isUnique = true;
        ArrayList<Album> cleanData = new ArrayList<>();
        for (Album a: albums){
            for (Album b: cleanData){
                isUnique &= !a.getAlbumTitle().equals(b.getAlbumTitle());
            }
            if(isUnique)
                cleanData.add(a);
            isUnique = true;
        }
        return cleanData;
    }

But I want to discard duplicates at the data collection stage (in the getAlbums method), since there recursion and discarding duplicates reduced the method's running time.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question