Using key and value in spinner without hashmap structure Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using key and value in spinner without hashmap structure without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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,


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.

We are here to answer your question about Using key and value in spinner without hashmap structure - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji