Ogulcan Orhan
Ogulcan Orhan

Reputation: 5317

How to sort HashMap as added in Android with ArrayAdapter

I have a HashMap<String,String> and there is a static method which returns this map to an Activity.

Method looks like this:

public static HashMap<String, String> getAll() {    
    HashMap<String, String> map = new HashMap<String,String>();

    map.put("ab", "value1");
    map.put("bc", "value2");
    map.put("de", "value3");

    return map;
}

I want to use that map with a spinner. So activity looks like this:

List list = new ArrayList<String>();
HashMap<String, String> map = Constants.getAll();

for (String key : map.keySet()) {
    list.add(Constants.getAll().get(key).toString());
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinTest = (Spinner)findViewById(R.id.spinTest);

spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        urlDebug.setText(list.get(arg2).toString());
    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

spinTest.setAdapter(adapter);

When I tried to run my application, no problem at all. But when I clicked on spinner, items not ordered as I added on getAll() method. I mean, order has to be ab - bc -de but it's ordered randomly.

What's not true?

Upvotes: 6

Views: 5334

Answers (3)

Yahel
Yahel

Reputation: 8550

Update : Answer by jitendra sharma is the best : A treemap costs a lot more than a linkedhashmap and adds nothing to your project if you only need to keep original insertion order.

Hashmap cannot get sorted. That's part of their efficiency.

If you need sorting, then use a TreeMap.

Good luck.

Upvotes: 2

Hubert
Hubert

Reputation: 1

You should either call adapter.notifyDataSetChanged() or spinTest.setAdapter(adapter) after you sorted your list.

spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        urlDebug.setText(list.get(arg2).toString());
    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

spinTest.setAdapter(adapter);
// TODO: Sort the list
// Some code here
adapter.notifyDataSetChanged();

Upvotes: 0

jeet
jeet

Reputation: 29199

in hashmap, insertion order is not maintained, so item inserted last may accessed first. If you want to maintain order of insertion, use linkedhashmap instead.

Upvotes: 7

Related Questions