How to get a value from an arrayList in Android?

Question:

I have the following ArrayList which filled with information from a database

ArrayList<HashMap<String, String>> employeeList;
employeeList = new ArrayList<>();
private static final String TAG_NAME = "name";
public static final String TAG_DESIGNATION = "designation";

Log.d("INICIA ","employeeList= "+employeeList);

In the Logcat it gives me the following:

D/INICIA: employeeList= [{designation=manager, name=rick}]

Everything works fine but I have a doubt how I could access the manager value found in the arrayList to be able to use it in a condition

Answer:

A. If there is only one pair of values

It is enough to obtain said value by the name of its key in the HashMap that you have created. The get (0) looks for the first (and in this case only value) within the map:

String sDesignation= employeeList.get(0).get("designation");

The variable sDesignation will have the value manager in this case.

B. If there are multiple pairs of values ​​on the map

If there are several pairs of values ​​in the array, the reading is usually done within a loop (for, while …).

Example with Iterator and While :

/*
 *Este ejemplo obtiene, en el caso de que haya varios valores, 
 *en la variable `key` la llave (designation, name...) 
 *y en la variable `value` los valores de cada llave (manager, rick...)
 */

Iterator myIterator = employeeList.keySet().iterator();
while(myIterator.hasNext()) {
    String key=(String)myIterator.next();
    String value=(String)employeeList.get(key);
}

Example with for loop

for (HashMap<String, String> map : employeeList)
     for (Entry<String, String> mapEntry : map.entrySet())
        {
        String key = mapEntry.getKey();
        String value = mapEntry.getValue();
        }
Scroll to Top