Skip to content Skip to sidebar Skip to footer

How To Sort Adapter (baseadapter) Based On Current Its Field

I have listviewadapter , it contains some fields like : status, notes, salesname, insertdate (txtTgglInsert), image. I want to do sorting based insertdate(txtTgglInsert) descending

Solution 1:

Since your Adapter is based on an ArrayList of objects, you can change your implementation to subclass ArrayAdapter (Docs: http://developer.android.com/reference/android/widget/ArrayAdapter.html)

publicclassListViewTimelineAdapterextendsArrayAdapter<URLPostClass> {

after that, sorting would be trivial:

ArrayList<URLPostClass> myListData = ...
ArrayAdapter<URLPostClass> adapter = newMyArrayAdapter<URLPostClass>(context, R.layout.my_layout, myListData);
adapter.sort(newComparator<URLPostClass>() {

    @Overridepublicintcompare(URLPostClass lhs, URLPostClass rhs) {
        return rhs.getTgglInsert().compareTo(lhs.getTgglInsert()); // flipped for reverse order
    }

});
myListView.setAdapter(adapter);

Solution 2:

Considering that you've got a Date field your Comaparator class would be like this

publicclassCustomDateComparatorimplementsComparator<DataProcessorResult> {
    SimpleDateFormatsimpleDateFormat=newSimpleDateFormat ("dd MMM yyyy");


@Overridepublicintcompare(DataProcessorResult lhs, DataProcessorResult rhs) {
    // TODO Auto-generated method stubDatelhsDate=null;
    DaterhsDate=null;

    try {
        lhsDate = simpleDateFormat.parse(lhs.getTgglInsert());
        rhsDate = simpleDateFormat.parse(rhs.getTgglInsert());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(lhsDate == rhsDate) {
        return lhs.getNamaSales().compareToIgnoreCase(rhs.getNamaSales());
    }else {
        return lhsDate.compareTo(rhsDate);
    }
    }
}

And then you can do this

Collections.sort(results, newCustomDateComparator());

just before you pass it to your custom adapter class.

Hope this helps you.

Post a Comment for "How To Sort Adapter (baseadapter) Based On Current Its Field"