I understand how initialize a spinner from String Array in the resources file String.xml. However my issue always is how to link things properly when you select something from drop down menu. For example let say that your string array looks something like that
Electricity
Gas
Other
So in onItemSelected listener, if I want to know what was clicked to take a certain action, then should I check the pos and act on it (given i know position in my string array as below
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch(pos){
case 1: // Electricity
break;
case 2: //Gas
break;
.
.
.
}
}
OR should I do Sting comparison like :
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent.getSelectedItemAtPos(pos).toString().equal("Electricity"){
} else if (......){
}
.
.
}
The advantage of first is it is cleaner but the problem I have to make sure that when I change the resource file, I would always keep track of updating indexes.
The second is safer but it seems to be “wordy” doing String compare.
I am not, maybe I am missing an optimum solution or what I suggested above is simply ok?
Please help experts, I would rather do something right the first time as I would have many spinners in my app 🙁
Thanks
Between the two of these, without question the first option. For one, it’s a switch statement so it’s an instant jump to the right handle, whereas with the second you have a linear line of comparisons until you reach the one that you want. Secondly, you’re using String comparison in the second which is slower and less safe than just doing an integer comparison. It’s a little more work if you plan on changing it a lot, but I think it’s the better way of the two, personally.