I have an item with id and value and I want to add them into a spinner. So when I select the item, I will get the id of it. I can only add itemValue as below and get the selected String.
Can anyone give me the solution for this?
List<String> list = new ArrayList<String>();
list.add("item 1");
list.add("item 2");
list.add("item 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final Spinner sp = new Spinner(this);
sp.setAdapter(dataAdapter);
Make a pojo class of your own say
Item
and add two fields in it, id and name.Then make a list of those items and write your own adapter for the spinner, and use it.
It will return you the whole object of the Item class when you click any item of it.
Else, if the item ids are the sequential then you can map them with the item ids too and can carry on with the same implementation, you have done right now.
But first approach is the recommended one, as you are developing using an Object oriented language and your data structures must represent the actual objects of your requirement in the application.
Create new enum:
than using spinner adapter:
items class
now adding items to array list like this
as you did in your code from here.. set onitemselected listener like this...