Priya
Priya

Reputation: 37

Get image order by time android

I have wallpaper application which have image saving function and we are displaying that images in my collection menu. I want display it as new saved first. There any chance to order images like that ? My codes for get images from data folder is like below.

public void getImages()
{
    File root = new File(Environment.getExternalStorageDirectory()+File.separator+"KaroShare/");
    File[] images = root.listFiles();
    arrayList.clear();
    if(images!=null){
        for(int i=0;i<images.length;i++) {
            if(images[i].getName().endsWith(".png") || images[i].getName().endsWith(".jpg") ||
                    images[i].getName().endsWith(".jpeg")) {
                String path = images[i].getAbsolutePath();
                arrayList.add(path);
            }
        }
    }
}

Let me know if someone have idea to do it. Thanks a lot !

Upvotes: 0

Views: 131

Answers (2)

Quick learner
Quick learner

Reputation: 11457

Try this

 public void getImages()
    {
        File root = new File(Environment.getExternalStorageDirectory()+File.separator+"KaroShare/");
        File[] images = root.listFiles();
        arrayList.clear();
        if(images!=null){
       Arrays.sort( images, new Comparator()
          {
             public int compare(Object o1, Object o2) {

              if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                return -1;
              } else if (((File)o1).lastModified() < ((File)o2).lastModified())   {
                return +1;
              } else {
                return 0;
            }
         }

    }); 
            for(int i=0;i<images.length;i++) {
                if(images[i].getName().endsWith(".png") || images[i].getName().endsWith(".jpg") ||
                        images[i].getName().endsWith(".jpeg")) {
                    String path = images[i].getAbsolutePath();
                    arrayList.add(path);
                }
            }

        }
    }

Upvotes: 0

Alvin Varghese
Alvin Varghese

Reputation: 689

You can sort the files with currentFile.lastModified().

Upvotes: 1

Related Questions