porthfind
porthfind

Reputation: 1619

Android: Using String resource file to fill a Spinner

I'm trying to fill a Spinner with the values of a array using the string resource file (strings.xml) but don't know why, the Spinner appears with no values.

Java code:

String[] measures = new String[]{};
Resources res = getResources();
Spinner sp1 = (Spinner) findViewById(R.id.spinner);

measures = res.getStringArray(R.array.measures);
List<String> list_measures = new ArrayList<String>(Arrays.asList(measures));

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_measures);
       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);

strings.xml

<resources>
    <string name="days">Days(d)</string>
    <string name="hours">Hours(h)</string>
    <string name="minutes">Minutes(min)</string>
    <string name="seconds">Seconds(s)</string>
 </resources>

arrays.xml

<resources>
    <string-array name="measures">
        <item>@string/days</item>
        <item>@string/minutes</item>
        <item>@string/seconds</item>
        <item>@string/hours</item>
    </string-array>
</resources>

I can't see where is the problem for my spinner appears with no values.

Upvotes: 1

Views: 3116

Answers (1)

Lalit Fauzdar
Lalit Fauzdar

Reputation: 6363

This is how you initialize an ArrayAdapter with string-array resource.

      final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
                this,android.R.layout.simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.measures)); //Your resource name

      sp1.setAdapter(arrayAdapter); //attaching the spinner to a spinner.

Upvotes: 6

Related Questions