简体   繁体   中英

Sort dates in descending order

I want to sort my object that has dates in descending order. Here is the code I use in my fragment -

int pos = adapter.contains(status.id);    
if (pos == -1) {
    myobj = new MyAdapter.Mymyobj();
    myobj.status = status;
    adapter.addItem(myobj);
} else {
    myobj = adapter.getItem(pos);
    myobj.status = status;
}
convertStringToDate(myobj.status.getTimeInString());
sortDates.add(convertedDate);
Comparator<Date> cmp = Collections.reverseOrder(null);
Collections.sort(sortDates, cmp);

adapter.notifyDataSetChanged();

private Date convertStringToDate(final String dateString) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM. HH:mm");
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return convertedDate;
}

The above code is not working..Nothing is happening actually. I want the list to be in descending order. Should I do something in adapter as well?

Take a look at this tutorial . It shows you how to use the Collections.reverseOrder() comparator. Basically, you're calling it wrong. You should use:

Collections.sort(sortDates, Collections.reverseOrder());

Note that I'm not passing null as parameter here.

Your code as given either is incomplete or has compile errors that make it impossible to answer.

However, for one thing, I must ask why you think it necessary to convert dates to strings just to sort them, when the standard Date class already implements Comparable?

For another, your convertDateToString() method catches DateParseException and prints them where no user will see them, and carries on as though nothing had happened, which would probably cause an NPE later in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM