简体   繁体   中英

How to sort Android Listview / HashMap

i need a little help with my listview / hashmap.

I want to sort my listView by int values (TAG_EPOCH).

During my search on internet i found out that i might need a LinkedHashMap or a TreeSet but i don't understand how to use them with my existing code.

Here is an example of my code:

protected void onCreate(Bundle savedInstanceState) {
    ...
    contactList = new ArrayList<HashMap<String, String>>();
    ...
}

static ArrayList<HashMap<String, String>> contactList;
private static final String TAG_EPOCH = "dateEpoch";

private class GetContacts extends AsyncTask<Void, Void, Void> {
    ...
    @Override
    protected void onPostExecute(Void result) {
        ListView dummyView = (ListView) findViewById(R.id.list);

        mAdapter = new MyCustomAdapter();
        for (int i = 1; i < contactList.size(); i++) {
            HashMap<String, String> c = contactList.get(i);
            mAdapter.addItem(TAG_EPOCH);
        }
        dummyView.setAdapter(mAdapter);
    ...
}

You can try to implement a Comparator In your class

class Contact implements Comparable<Contact> 

Then add this:

public static final Comparator<Contact> INTEGER_COMPARATOR = new Comparator<Contact>() {
    // Overriding to sort on your integer
    public int compare(Contact c1, Contact c2) {
        return c1.integer - c1.integer;
    }
};

Then sort it using:

Collections.sort(list, Contact.INTEGER_COMPARATOR);

You should sort your listview?

Set a list of items in the adapter like

ArrayList list = new ArrayList();

// Add values to list

sorting an arraylist is easier with Compare

Sorting ArrayList

您可以使用Collections.sort()方法对ArrayList进行排序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM