user4297729 user4297729 - 28 days ago 8
Android Question

Java - for loop cycling through string array

So I'm new to programming. I have a string array named values that has about 150 strings in it. Instead of using a ton of if statements I wan't to to use a for loop that each time it cycles through the loop increments to the next element in the array. I'm sure it's a super simple fix but I just can't solve it. Thanks for any advice!

routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String route = values[position];

int i;
for (i=0; i < values.length;i++) {

if (route.equals(values[0])) {

Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[0]);
startActivity(intent);
}
values++;
}
/*if (route.equals(values[0])) {

Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[1]);
startActivity(intent);

}
if (route.equals("Main Wall")) {

Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", "Map of Main Wall");
startActivity(intent);

}
if (route.equals("1. Shark Bait - 5.9")) {

Intent intent = new Intent(MainActivity.this, RouteDetails.class);
intent.putExtra("route", "Shark Bait");
startActivity(intent);

}
*/
}

Answer

Inside of the loop, replace the hard coded 0's with "i". This will allow your code to be ran for each iteration of the loop. For example, the i will be replaced with 0, then 1, then 2, etc.

for (int i=0; i<values.length; i++) {

 if (route.equals(values[i])) {

    Intent intent = new Intent(view.getContext(), RouteDetails.class);
    intent.putExtra("route", routeDetail[i]);
    startActivity(intent);
 }
}

Also, there is no need to add a counter for values at the end, since it is handle by the i++ in the for loop. Hope that helps!

Comments