user6319790 user6319790 - 1 year ago 119
Java Question

Using key and value in spinner without hashmap structure

I have list of keys and values,
key = is a String of id from table.
value = is a String of name,

I want to show inside spinner view only the vaulues without the Ids, but after the user cliked on some item I need to get the Id of the selected item, and using it in code.
How can I implement this structure whitout using hashMap or many foreach statements?

Thank you,

Answer Source

Create a POJO class and pass an ArrayList of your custom objects to your spinner.

class MyClass{
    private String id;
    private String key;

    public MyClass(String id, String value) { = id;
        this.value = value;

    public String getId() {
        return id;

    public void setId(String id) { = id;

    public String getValue() {
        return value;

    public void setValue(String value) {
        this.value = value;

    public String toString() {
        return value;

Overriding toString() method is important. That's what will be shown in spinner item.

You can pass it to your ArrayAdapter like that:

ArrayAdapter userAdapter = new ArrayAdapter(this, R.layout.spinner, myList);

When a user clicks on an item, getSelectedItem() method will give you object. You can get the id from there.

From the docs:

A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.