Sarah Phil
Sarah Phil

Reputation: 263

Sorting using SimpleAdapter

I want to sort my Listview according to some value in my application but i dont know how to code it. I researched and found that people are using comparator and collection to sort the arraylist. Basically, i want to sort by some status such as accepted or rejected. The value is store in TAG_ACCEPT_REJECT and display in R.id.applicantStatus.

Below is my code:

adapter = new SimpleAdapter(
                ApplicantJobStatusActivity.this,
                applicantsList,
                R.layout.list_applicant_status,
                new String[] { TAG_UID, TAG_NAME,
                               TAG_ACCEPT_REJECT,
                               TAG_ACCEPT_REJECT_DATETIME },
                new int[] { R.id.applicantUid,
                            R.id.applicantName,
                            R.id.applicantStatus,
                            R.id.accept_reject_datetime });
setListAdapter(adapter);

I want to know how and where to place the sorting code using comparator and collection to rearrange my ListView.

Upvotes: 0

Views: 1220

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

- Use Arrays.sort() before assigning the Array to the Adapter.

- Or you can Use Collections.sort(Collection c) with Comparable Interface,

- Or Collections.sort(Collection c, Comparator cp) with Comparator Interface, with Colletions like ArrayListbefore assigning it to theAdapter`.

///////////////////////// Edited Part//////////////////////////

See this below link, which contains all the examples of sorting an Array, ArrayList etc using various techniques.

http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Upvotes: 1

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28551

You should sort your list applicantsList prior to passing it to your adapter. You can then use the Collections.sort approach. Something like that:

Collections.sort(applicantsList, new Comparator<T extends Map<String, ?>> {
  public int compare(T map1, T map2) {
    if (!map1.has(TAG_ACCEPT_REJECT)) return -1;
    if (!map2.has(TAG_ACCEPT_REJECT)) return 1;

    // Assumes the objects you store in the map are comparables
    return map1.get(TAG_ACCEPT_REJECT).compareTo(map2.get(TAG_ACCEPT_REJECT));
  }
});

Upvotes: 3

Related Questions