Home » Android » Spinner setting ArrayList<String> as values

Spinner setting ArrayList<String> as values

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m working on a spinner and what I’m trying to achieve is set the Arraylist as the values for the selected item on the spinner but what I’m getting is the arrayList is the one being displayed as choices under spinner.

This is how I do it :

final Spinner spinner = (Spinner) findViewById(R.id.numSpinner);
    ArrayList<String> numArr = new ArrayList<String>();
    numArr.add("09054802841");
    numArr.add("09123456789");
    ArrayAdapter<String> numAdapter = new ArrayAdapter<String>(this, 
    android.R.layout.simple_spinner_dropdown_item, numArr);
    spinner.setAdapter(numAdapter);

and this is how I get the value from the spinner and this is where I know the error occurs because Recipient_value_array is the values I get when I select an Item on the spinner where It should be the Arraylist values. How do I set It properly?

 itemSpin = getResources().getStringArray(R.array.recipient_value_array)[spinner.getSelectedItemPosition()];
Answers:

To get the value of Spinner add a setOnItemSelectedListener

like:

    final Spinner spinner = (Spinner) findViewById(R.id.numSpinner);
    final ArrayList<String> numArr = new ArrayList<String>();
    numArr.add("09054802841");
    numArr.add("09123456789");
    ArrayAdapter<String> numAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, numArr);
    spinner.setAdapter(numAdapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String value = numArr.get(i);
            Log.i("MainActivity", "Response: " + value);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });