Dane Lowrey Dane Lowrey - 2 years ago 96
Java Question

Assign values to string-array items in a spinner

I have a spinner in which I would like to select a state in the U.S. like 'Texas', and then capture that selection. I want the display on the spinner to be "Texas", "California", "Utah", etc, but when the user selects it, and I capture the value, I want the value to be '57' instead of "Texas". I know I can just do:

String selection = my_spinner.getSelectedItem().toString();
int selectionVal;

if(selection = "Texas"){
selectionVal = 57;

But I would have to do that for a lot of states. Is there a way to do it like I explained above? If not, what would be the most efficient way of doing this? Thank you.

Answer Source

You can create a HashMap that contains the state name as key and it's equivalent number as value.

The after the user selects a value from the Spinner, all you need is to fetch the value from the HashMap and display it.

For example, you can try something like this

HashMap<String,Integer> myMap=new HashMap<String,Integer>();


You can add all values to this HashMap.

Now when you get the selected option from the Spinner, you can fetch the value from HashMap.


Hope this helps :)

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