farha
farha

Reputation: 69

How to find key from HashMap

 JSONObject json = new JSONObject(result);
                       Iterator<?> keys = json.keys();
                        while( keys.hasNext() ){
                             key = (String)keys.next();
                           item = json.getString(key);
                           mList.add(item);
                           ItemsHashMap.hmstock.put(key, item);

Please can any one tell me how to find key from this code example like{17=Common English,16=Basic english}.i want get onliy key means (17)from this please help me...because these all 18 items show in listview

Upvotes: 3

Views: 3421

Answers (2)

Tarsem Singh
Tarsem Singh

Reputation: 14199

Try by

public void onItemClick(AdapterView<?> parent, View view, int
         position,
         long id) {

         String name = mList.get(position);
         Iterator itr = ItemsHashMap.hmstock.keySet().iterator();
         while (itr.hasNext()) {
                String key2 = (String) itr.next();
                if (ItemsHashMap.hmstock.get(key2).toString().equals(name) {
                    keyId = Integer.parseInt(key2);// parsing to int because i am assuming KeyId variable is of int 
                    break;
                }
            }
         Toast.makeText(getBaseContext(), "" + keyId,
         Toast.LENGTH_SHORT).show();
         // keyId Shows the null Value
         }

Upvotes: 1

Bhoomika Brahmbhatt
Bhoomika Brahmbhatt

Reputation: 7415

EDIT

1)Change

ItemsHashMap.hmstock.put(key, item);

to

ItemsHashMap.hmstock.put(item, key);

2)so now u are actually displaying item where in hashmap it will be stored as "key".so whenever u click on listview u get selected text as item..so item became key of your map.

key=Entertainment English; value=1;

3)now pass your item to get its value;

if(hashMap.containsKey(item))//here item is key;item=Entertainment English
  {

         String value=hashMap.get(item);
//so it will return value of this key
//value="1";
   }

Upvotes: 0

Related Questions