I have a globally defined ArrayList as ArrayList<Map<String, String>> mContactList;.
Now, in one of the methods, I am defining a HashMap like this:
Map<String, String> NamePhoneType = new HashMap<String, String>();
NamePhoneType.put("Name", contactName); //contactName is returned from a query
NamePhoneType.put("Phone", phoneNumber); //phoneNumber is returned from a query
mContactList.add(NamePhoneType);
So mContactList now looks like [{Name=Abc, Phone=123}, {Name=def, Phone=456}...]
Now when I try to iterate over the mContactList using the following, I always get the key as 'Phone' and Value as '123' or '456' depending on the index.
public void onItemClick(AdapterView<?> av, View v, int index,long arg) {
Map<String, String> map = (Map<String, String>) av.getItemAtPosition(index);
Iterator<String> myVeryOwnIterator = map.keySet().iterator();
while (myVeryOwnIterator.hasNext()) {
String key = (String) myVeryOwnIterator.next();
String value = (String) map.get(key);
getNumber.setText(value);
}
}
});
I want the Name and the Phone of the selected index in 2 separate strings. How do I do that?
Instead of having a Map as you do, I would recommend creating a class called
Contact. Your ArrayList would then be declared asThe Contact class would look like
Whenever you end up with nested data structures, it’s usually a sign to rethink your design as there’s usually a better way to do it.
However, to answer your question; note what this piece of code is doing.
You are iterating through a map which (appears to) always have two pairs:
There’s no need to iterate through the Map to get the values you desire. Your code should look like: