Android listview display as alphabetic order

1.3k Views Asked by At

I got the response from Json and need to display the result as in ordered name. After implementing the Hashmap I realized that it was not sorted alphabetically How do i do that?

public ArrayList<HashMap<String, String>> contactList= new ArrayList<HashMap<String, String>>();

Collections.sort(contactList, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

Code:

protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (pDialog.isShowing())
        pDialog.dismiss();
    SimpleAdapter adapter = new SimpleAdapter(
            HomeActivity.this, contactList,
            R.layout.list_item, new String[] {TAG_FNAME}, new int[] {R.id.textView1});
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                View view, int position, long ids) {
            Intent i = new Intent(getApplicationContext(),
                    SingleListActivity.class);
            HashMap<String, String> contact =  contactList.get(position);
            i.putExtra("id", id);
            i.putExtra("firstName", firstname);
            i.putExtra("lastName", lastname);
            i.putExtra("headline", headline);
            i.putExtra("pictureUrl", pictureUrl);
            i.putExtra("url", url);
            startActivity(i);
        }
    });

In this it contains both first name and last name how do i do that?

2

There are 2 best solutions below

0
On

To sort ArrayList of HashMap , use this code.

Collections.sort(ArrayList,new Comparator<HashMap<String,String>>(){
public int compare(HashMap<String,String> mapping1,HashMap<String,String> mapping2){
    return mapping1.get("Name").compareTo(mapping2.get("Name"));

}

In most case, HashMaps have same key , so you can use this code.(Change the "Name" to your key). Replace ArrayList with your Arraylist name, contactList in your case.

Hope this helps :)

0
On

If ur checking for "How sort an ArrayList of HashMaps holding several key-value pairs each" then it is already discussed, please have a look stackoverflow.com/questions/5369573

If ur checking for "android-listview-display-as-alphabetic-order" then look this stackoverflow discussion stackoverflow.com/questions/12559843