With filling a spinner with an object field

Asked

Viewed 3,080 times

2

I have a Spinner in my Activity, need to make your items to be the names (field) of a Arraylist of objects, and that when selected, I be returned the id of the same to be able to perform a new operation.

For example:

My contact object

public class Contato {

    String nome;
    int id;
    //getters e setters
}

I tried to do it this way, but in the Spinner is displayed only the address of the object in the application memory.
How can I have the name obtained from each object displayed on Spinner and return the id of the same?

// Uma lista contendo os objetos
ArrayList<Contact> contactlist= new ArrayList<Contact>();
contactlist.add("Gabe");
contactlist.add("Mark");
contactlist.add("Bill");
contactlist.add("Steve");

// Array Adapter que é definido como adapter do spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, contactlist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

1 answer

2


The ideal way is to write an Adapter for this purpose.

Not wanting to have this "job" and using the Arrayadapter, an expeditious way is to take advantage of how the Arrayadapter works.

The Arrayadapter uses the method toString() of the class used as an Arraylist item to get the value to display.
The value that the method toString() return is the one who the Spinner present.

In class Contact do the Override of the method toString() in order to return the field nome:

public class Contato {

    String nome;
    int id;
    //getters e setters

    @Override
    public String toString()
    {
        return nome;
    }
}

To obtain the id of the selected contact make:

Contato contato = (Contato)spinner.getSelectedItem();
int id = contato.id;

Or more directly:

int id = ((Contato)spinner.getSelectedItem()).id;
  • Thank you very much! It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.