-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.

7
  • Could you please explain what you mean more clearly? Commented Nov 23, 2018 at 13:04
  • Do you mean something like that Change String-Array in Strings.xml to ArrayList ? Commented Nov 23, 2018 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<String> object Commented Nov 23, 2018 at 13:10
  • 1
    @koman900 take a look at this question stackoverflow.com/questions/32127374/… Commented Nov 23, 2018 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? Commented Nov 23, 2018 at 13:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.