简体   繁体   English

按降序排列日期

[英]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. 它显示了如何使用Collections.reverseOrder()比较器。 Basically, you're calling it wrong. 基本上,您在说错。 You should use: 您应该使用:

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

Note that I'm not passing null as parameter here. 请注意,我没有在此处传递null作为参数。

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? 但是,有一件事,我必须问为什么当标准Date类已经实现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. 另外,您的convertDateToString()方法将捕获DateParseException并将其打印在没有用户看到的地方,并且好像什么都没发生一样继续进行,这很可能在代码的后面引起NPE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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