Tomasz Okraszewski Tomasz Okraszewski - 6 months ago 46
Java Question

Example for sorted String-array in Spinner

Hi I want to show alphabetical sorted array name="planets_array" in spinner.
I found some info about .sort collections and array list but nothing of let me to understand how it's working.
So please help me and show me on example.
I have in strings.xml:

<string-array name="planets_array">
<item>Dein Ziel</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>


And in Activity.java:

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Answer

1. Sort planets arrays.

String[] planetsArray = getResources().getStringArray(R.array.planets_array);
List<String> planetsList = Arrays.asList(planetsArray);
Collections.sort(planetsList); //planetsArray will be sorted

2. Pass sorted array list to the Adapter.

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, planetsList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);