I am trying to create an item list, diffrent for each i and j variable. My code is:
if (i == 0) {
if (j == 0) {
final CharSequence[] items = {"4:45", "5:00"}
} else if (j == 1) {
final CharSequence[] items = {"4:43", "4:58"}
} else if (j == 2) {
final CharSequence[] items = {"4:41", "4:56"}
} else {
final CharSequence[] items = {"4:38", "4:53"}
}
…
new AlertDialog.Builder(this)
.setTitle("Hours")
.setItems(items,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
// getStation(i);
}
})
.show();
}
I get an error in the line .setItems(items,:
items cannot be resolved
I think that the compiler thinks that the CharSequence[] items may not be initialised or something…
How can I make this programme run?
The problem is variable scoping.
Here we have two local variables
iwho goes out of scope immediately after they’re declared and initialized. Ifjneeds the value ofi, theniwould have to be declared in a larger scope.(It should be mentioned that this is exactly the kind of scenarios where the ternary operator excels, i.e.)
In your specific case, unfortunately the array initializer shorthand can only be used to initialize upon declaration. That is:
You can pull out the declaration of
itemsoutside theifand write the verbose code for each case (see Joachim Sauer’s answer), but a more concise code is to use array-of-arrays instead.This technique works well in this case, but in the more general case you want to use a
Mapor something similar.Note: It’s not explicit in the original code, but this works if
jcan either be0,1,2, or3. If you want the last option to apply whenjis any value other than0,1,2, then you have to check for that and set it to3before this code.