Sun Sun - 1 year ago 62
Java Question

For Loop to get Data from custom ArrayList

I am just trying to get

state name
state id
, for an example: my strId is 1, but not getting state name which belongs to strId 1, everytime getting last state name found in

for (int i=0; i<stateModelArrayList.size(); i++) {
String strId = stateModelArrayList.get(i).getId().toString();
if(strId.equals(strState)) {
Toast.makeText(MainActivity.this, strId+" : "+strState, Toast.LENGTH_SHORT).show();
strStateName = stateModelArrayList.get(strId).getName().toString();

Answer Source

I guess that your mistake is here:

strStateName = stateModelArrayList.get(strId).getName().toString(); 

It should be:

strStateName = stateModelArrayList.get(i).getName().toString(); 

If you don't want to get the last value don't forget to call break to stop the loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download