Samantha Withanage
Samantha Withanage

Reputation: 3851

take images in a folder into an array

In my android project, I have had to store images from the sd card in to an array. I can filter and get all the images in the folder. But what i really need to do is filter and get some specific images instead of all the images. My code segment is,

File[] imagelist = filePath.listFiles(new FilenameFilter(){  
            public boolean accept(File dir, String name)  {  
                return ((name.endsWith(".jpg"))||(name.endsWith(".png")));
            }  
        });

So, can someone help me with some helpful code segment. Thank you!

Upvotes: 0

Views: 1349

Answers (1)

Numeron
Numeron

Reputation: 8823

Ok, so if you have a list of names you want in a String array, then for every file that runs through the filter you will have to loop over the list and compare the name of the file against the array to see if it exists. If it does then its one you want.

File[] imagelist = filePath.listFiles(new FilenameFilter(){
  public boolean accept(File dir, String name){
    if(!(name.endsWith(".jpg") || name.endsWith(".png")) return false; // Only need images
    for(String validName: namesArray){
      // If the names in the list include the file extention then use this line
      if(name.equals(validName)) return true;
      // Otherwise If the names in the list don't include the file extention then use these lines
      if(name.endsWith(".jpg") && name.substring(0, name.lastIndexOf(".jpg")).equals(validName)) return true;
      if(name.endsWith(".png") && name.substring(0, name.lastIndexOf(".png")).equals(validName)) return true;
    }
    return false;
  }  
});

Upvotes: 1

Related Questions