Mohan
Mohan

Reputation: 23

How to sort the recyclerview based on date

Posting for the second time....

Here is my question

This is about Android. I am implementing recycler view which have heterogeneous layouts.I am passing a static data to it. So if its Layout A it takes object A data. If its Layout B it takes Object B data and so on.

Example :

List.add(new A("May 27",2,3000$));

List.add(new B("April 21",2,"Place1",2000$));

List.add(new c("March 20","from place","toplace",5000$));

My Question is how i can sort the Recyclerview based on the date that we have passed for each object. let say "March 20" comes first so it has to appear at top in the recyclerview and "May 27" should display last in the Recyclerview.

I can use Collections.sort() by passing the list and the implementation of comparator interface as second argument. by taking away the date field and inserting it into parent class D and making class A,B,C inherit Class D. but its not working in my case.

Class D {

    private String date;

    // getter and setter method

}

Class A extends D{}

Class B extends D{}

Class C extends D{}

IN RecyclerViewAdapter

//onCreateViewHolder()


//OnBindViewHolder()

//getiewType()


//Creating list of data

private ArrayList<Object> getData(){

        ArrayList<Object> list = new ArrayList<>();

        for(int i=0;i<=20;i++) {

            list.add(new A("MAY 23", 1, 3000$));

            list.add(new B("April27", 1, 2, 3400$));

            list.add(new C("New york" "March 28", 1000$, 2, 2));

        }


    Collections.sort(list, new Comparator<D>() {

        @Override
        public int compare(D l1, D l2) {

            SimpleDateFormat sdf = new SimpleDateFormat("MMM dd", Locale.ENGLISH);

            Date d1=null;
            Date d2= null;

            try {
                d1=sdf.parse(String.valueOf(l1.getDate()));

                 d2= sdf.parse(String.valueOf(l2.getDate()));

             } catch (ParseException e) {

                e.printStackTrace();
            }

            if(d1 != null && d1.after(d2)){

                return -1;

            }else{

                return 1;}
            }

        return 0;

##error "unexpected token" /// or if do something here it shows entire block ##as error :

Wrong in 2nd argument

Found : java.util.comparator(D)

required : java.util.comparator(Object)

    });

    return list;

}

can some one please help me on this question. Thanks in advance

Upvotes: 1

Views: 3008

Answers (1)

user7774943
user7774943

Reputation:

try changing that Collections.sort(list, new Comparator<D>() {to Collections.sort(list, new Comparator<Object>() {

Upvotes: 1

Related Questions