-2

I have a spinner, created in an XML file:

<Spinner
    android:id="@+id/unitSpinner"
    android:entries="@array/units" />

With its entries defined in array.xml

<string-array name="units">
    <item>g</item>
    <item>kg</item>
    <item>ml</item>
    <item>l</item>
    <item>szt.</item>
    <item>op.</item>
</string-array>

Now in my Java file I want to create an ArrayList<String> which contents after feeding it with Spinner's entries would be:

["g", "kg", "ml", "l", "szt.", "op."]

My Java code looks like this:

Spinner unit = (Spinner) findViewById(R.id.unitSpinner);
ArrayList<String> array = new ArrayList<>();
//pass information from unit to array

EDIT:

This question differs from many questions like Android : Fill Spinner From Java Code Programmatically as I don't want to fill Spinner with an Array, but the opposite way.

Elgirhath
  • 409
  • 1
  • 7
  • 15
  • Could you please explain what you mean more clearly? – Elgirhath Nov 23 '18 at 13:04
  • Do you mean something like that [Change String-Array in Strings.xml to ArrayList](https://stackoverflow.com/questions/19127071/change-string-array-in-strings-xml-to-arraylist/19127223) ? – user141080 Nov 23 '18 at 13:05
  • @user141080 this question is helpful, but please check out my edited Java code: I would like to pass entries from my Spinner object to the ArrayList object – Elgirhath Nov 23 '18 at 13:10
  • 1
    @koman900 take a look at this question https://stackoverflow.com/questions/32127374/android-how-to-get-all-items-in-a-spinner – Marina Budkovets Nov 23 '18 at 13:22
  • 2
    This doesn't really make sense. You already know exactly what those values are. What is the point of building an `ArrayList` from the `Spinner` values? – Mike M. Nov 23 '18 at 13:43
  • @MikeM. e.g. you get a `String unit` from other function. Then you want to make this unit selected in the `Spinner` using `spinner.setSelection(int index)`. You need to know what is the index of `String unit` in the `Spinner`. My other functions allow you to programatically add or edit the values in `Spinner` so reading an `ArrayList` from `array.xml` doesn't do the job. – Elgirhath Nov 23 '18 at 15:06
  • Ah, that makes more sense. You should've mentioned in the question that the `Spinner`'s values are editable. – Mike M. Nov 23 '18 at 15:08

1 Answers1

4

You can get the list from the XML array directly. no need to get ti from the spinner

String[] ss  = getResources().getStringArray(R.array.units);
ArrayList<String> array = Arrays.asList(words);

if this aproach does not work with you you can try to get all the items fom the spinner via loop

    for( int i = 0  ; i< unit.getAdapter().getCount() ; i++ ){
                array.add ( ss.getAdapter().getItem( i ) )

}

Hope this will help.

Diaa Saada
  • 1,026
  • 1
  • 12
  • 22