Search code examples
androidlistviewandroid-arrayadapterbaseadapter

Sorting adapter on particular array


I have a collection of object assigned to an adapter set to a listview. I know how to sort an adapter value when it contains single object. My question is how do I sort the collection only on the data datatype. Below is my collection

you = new MyVideoAdapter(getActivity(),vDancers,video, vName, vDanceStyle, vOwner, dCountry, vPic, vCreated, fullname,
                        vLikes,vComments, vViews,vRepost, objectID, nLikes, nComments, nRepost, vUserID, postType);
                //you.comp
                listView.setAdapter(you); 

I want to sort this adapter (you) by the vCreated which is an array of dates. Thanks in advance for any help.


Solution

  • For those looking for a solution, this is how I went about it (I don't know if its the best solution but it does work for my case). 1. Instead of populating the adapter with the individual arrays, I created an ArrayList and populated it with my arrays.I sorted it using compareTo().

    public class Items implements Comparable<Items>{
    
    private final Number vLikes; private final Number vComments; private final Number vRepost; private final Number vViews;
    private  final Date vCreated;
    
    public Items(Number vLikes, Number vComments, Number vViews, Number vRepost, Date created) {
        this.vCreated = vCreated;
        this.fullname = fullname;
        this.vLikes = vLikes;
        this.vComments = vComments;
        this.vViews = vViews;
        this.vRepost = vRepost;
    }
    
    @Override
    public int compareTo(Items o) {
        if (getvCreated() == null || o.getvCreated() == null)
            return 0;
        return o.getvCreated().compareTo(getvCreated());
    }
    
    public Number getvLikes() {
        return vLikes;
    }
    
    public Number getvComments() {
        return vComments;
    }
    
    public Number getvViews() {
        return vViews;
    }
    
    public Number getvRepost() {
        return vRepost;
    }
    public Date getvCreated() {
        return vCreated;
    }
    }
    

    2. I then sort the arraylist using the date column and using Collections to apply the sorting.

    List<Items> myList = new ArrayList<Items>();
    Items item = new Items(a,b,c,d);//a, b, are my variables
    myList.add(item);
    

    3. I populated my adapter with the sorted arraylist.

    Collections.sort(myList);
    you = new MyAdapter(getActivity(), myList);
    

    I hope this helps.