How to sort files using datetimestamp

孤街醉人 提交于 2019-11-29 12:56:05
Niranj Patel

If you getting data in reverse order than you can use reverse loop.

Try below loop

for (int i = files.length-1; i >= 0; i--)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}

instead of

 for (int i = 0; i < files.length; i++)
 {
      file = files[i];
      Log.d("Count",file.getPath());
      it.add (file.getPath());
  }

or sort data with particular field

Sort array data before using in for loop and use same loop..

Arrays.sort(files, new Comparator<Object>()
{
    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 < files.length; i++)
 {
      file = files[i];
      Log.d("Count",file.getPath());
      it.add (file.getPath());
  }

Use MediaStore ContentProvider for this job Save the image using MediaStore using this method

And you can query the image using this method

Set the order by as MediaStore.Images.Media.DATE_TAKEN

You can use the Collections.sort method in your list adapter to sort the values according to the image file name like:

Collections.sort(ImageList, new Comparator<String>() {
  int compare(String obj1, String obj2) {
        return obj1.compareTo(obj2);
  }
});

compareTo method and also compareToIgnoreCase method, use wichever you think is appropriate, and also, you can experiment with obj1 and obj2, that is, you could swap the condition to:

 return obj2.compareTo(obj1);

That way your list will be sorted. Hope that helps!

EDIT:

Since you know that the format is _ and then -.jpg, what you can do is in the comparator split the value from - like:

Collections.sort(ImageList, new Comparator<String>() {
  int compare(String obj1, String obj2) {
        String[] obj1Arr = obj1.split(-);
        String[] obj2Arr = obj2.split(-);

        obj1Arr = obj1Arr[1].split("."); // to just get the counter value
        obj2Arr = obj2Arr[1].split(".");

        return obj1Arr[0].compareTo(obj2Arr[0]);
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!