Android: better way to get an integer from a spinner
android, arrays, java, spinner
Solution
What you could do is first getting the array from the resources, then create an Integer array and give it to an `ArrayAdapter<Integer>` instead. Something like this:
Spinner spinner = (Spinner) findViewById(R.id.num_cells_spinner);
String[] array = getResources().getStringArray(R.array.settings_cells_array);
Integer[] intArray = new Integer[array.length];
for(int i = 0; i < array.length; i++) {
intArray[i] = Integer.parseInt(array[i]);
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_dropdown_item, intArray);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
Then just cast the result of `getSelectedItem()` to `Integer` :
Integer i = (Integer)spinner.getSelectedItem();
Problem
I have a spinner filled with integer values, and I'm trying to extract the selected value. I managed to do with the following line of code: ``` Integer.decode(spinner.getSelectedItem().toString()) ``` but this seems like a lot of calls for what should be a simple operation. I'm creating the spinner using a string-array defined as follows: In the strings.xml ``` <string-array name="settings_cells_array"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> </string-array> ``` In the activity onCreate function: ``` Spinner spinner = (Spinner) findViewById(R.id.num_cells_spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.settings_cells_array, R.layout.my_layout); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(R.layout.my_layout); // Apply the adapter to the spinner spinner.setAdapter(adapter); ``` In my mind, since the spinner is created with a string-array, the `.toString()` call seems excessive, but I imagine that's leaving room for flexibility with adapters and spinners built out of custom objects or something fancy like that. Anyway, my question is this: is there a better way to extract an integer from a spinner defined this way, or alternatively, is there a better way to set up my spinner such that it plays more nicely with ints?