With filling a spinner with a field of an object

2

I have a Spinner in my Activity , I need to make your items the names (field) of an ArrayList object, and which when selected, is 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 this, but in Spinner only the address of the object in the application's memory is displayed. How can I get the name of each object in Spinner displayed and return the id of it?

// 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);
    
asked by anonymous 14.01.2016 / 23:03

1 answer

0

In the Contact class, make the Override method toString() to return the nome :

public class Contato {

    String nome;
    int id;
    //getters e setters

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

The value that the toString() method returns is that Spinner will display.

To get id of the selected Contact do:

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

Or more directly:

int id = ((Contato)spinner.getSelectedItem()).id;
    
14.01.2016 / 23:21