Android: the best way to get an integer from a counter

I have a counter filled with integer values โ€‹โ€‹and I am trying to retrieve the selected value. I managed to make the following line of code:

Integer.decode(spinner.getSelectedItem().toString())

      

but it looks like a lot of calls to what should be a simple operation.

I am creating a counter using a string array defined like this:

In strings.xml file

<string-array name="settings_cells_array">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
</string-array>

      

In the 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 opinion, since the spinner is .toString()

constructed with a string array, the call seems overkill, but I guess leaving room for flexibility with adapters and spinners built from custom objects or something similar.

Anyway, my question is this:
is there a better way to extract an integer from the above counter, or, alternatively, is there a better way to tune my counter so that it matches int s in a nicer way ?

+3


source to share


1 answer


What you can do is first get an array from resources and then create an Integer array and pass it instead ArrayAdapter<Integer>

. Something like that:

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 put the result getSelectedItem()

in Integer

:

Integer i = (Integer)spinner.getSelectedItem();

      

+3


source







All Articles