Thursday, June 13, 2013

Sorting the list Objects Based on Date Wise (format):

Sorting the list Objects Based on Date Wise (format):

POJO Class Or Persist Class:
----------------------------
public class News {
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getDescription() {
return description;
}
public News(String title, String date, String description) {
super();
this.title = title;
this.date = date;
this.description = description;
}
private String title, date, description;
}


In Your Activity Class:
-------------------------
private SimpleDateFormat formatter, FORMATTER;
FORMATTER = new SimpleDateFormat("MMMMM dd, yyyy", Locale.ENGLISH);
private ArrayList<News> newsList = new ArrayList<News>();

newsList.add(new News("Title1", "January 26, 2013"), "DESC 1");
newsList.add(new News("Title2", "August 15, 2011"), "DESC 2");
newsList.add(new News("Title3", "October 02, 2012"), "DESC 3");
newsList.add(new News("Title4", "November 05, 2013"), "DESC 4");
newsList.add(new News("Title5", "August 15, 2012"), "DESC 5");

after finishing adding to list:
/* sorting of objects begin here  */  
Collections.sort(newsList, new customComparator());


Make this class as Sub Class of your activity class.
public class customComparator implements Comparator {
   public int compare(Object  object1, Object  object2) {
    News e1 = (News) object1;
    News e2 = (News) object2;
   
    Date d1 = null;
       Date d2 = null;
       try {
           d1 = FORMATTER.parse(e1.getDate());
           d2 = FORMATTER.parse(e2.getDate());
       } catch (ParseException e) {
           e.printStackTrace();
       }
       return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
   //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
   }
}

No comments: