gosulove
gosulove

Reputation: 1645

Android get the Key in Hashmap in Arraylist within Listview CHOICE_MODE_MULTIPLE

I parse json data and display it in listview with CHOICE_MODE_MULTIPLE. I trying to get the key of a Hashmap in my case but I only manage to get the value.

enter image description here

Json data

57->Steak Doness
58->Size
59->Cooking Method
63->Coldness

Here is the coding

String option_data = jsonObject.getString("option_data");
JSONObject jsonObject1 = new JSONObject(option_data);
Iterator<String> iterator = jsonObject1.keys();
ArrayList arrayList = new ArrayList<HashMap<String, String>>();

HashMap<String, String> map = null;
while (iterator.hasNext()) {
    String id = iterator.next();
    String name = jsonObject1.getString(id);
    map = new HashMap<String, String>();
    map.put("id", id);
    map.put("name", name);
    arrayList.add(name);
}

ArrayAdapter adapter = new ArrayAdapter<String>(item_add.this, android.R.layout.simple_list_item_multiple_choice, arrayList);
final ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String selected = "";
        SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
        for (int i = 0; i < listView.getCount(); i++) {
            if (sparseBooleanArray.get(i)) {
                selected += listView.getItemAtPosition(i).toString() + ",";
            }
        }
        Log.d("selected", selected);
    }
});

With the logcat, it shows

D/selected: Steak Doness,Size,

However, what I want to get is the Key in Hashmap which means "id" when click the button . Anyone knows how to do it?

Upvotes: 0

Views: 493

Answers (1)

Sreehari
Sreehari

Reputation: 5655

Use the following way to iterate and find values of keys

        HashMap <String,String> mapOne= new HashMap();
        mapOne.put("1","1value");
        mapOne.put("2","2value");
        mapOne.put("3","3value");

        for(Map.Entry<String, String> mapEntry : mapOne.entrySet()){
        if (mapEntry.getValue().equals("3value")) {
            //System.out.println(mapEntry.getKey());
            Log.d("selected", mapEntry.getKey());
        }
    }

Upvotes: 1

Related Questions