Populating Android Spinner with List of Objects

Joy picture Joy · Sep 6, 2013 · Viewed 16.8k times · Source

I'm populating my spinner with user object in order to work later with the user ID but the display of the user lists shows the address of the object I guess.

So my question is how to display only one attribute of the object, in the case of user name, but still populate the spinner with the whole object

Here's my code:

User user1 = new User("user1",24);
User user2 = new User("user2",26);

// Creating adapter for spinner
List<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);

ArrayAdapter<User> dataAdapter = new ArrayAdapter<User>(this, 
    android.R.layout.simple_spinner_item, users);

// Drop down layout style - list view
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Spinner _EmpSpinner =  null;
_EmpSpinner = (Spinner) findViewById(R.id.EmployeesSpinner); 

// attaching data adapter to spinner
_EmpSpinner.setAdapter(dataAdapter);

And this is what it displays:

Answer

Szymon picture Szymon · Sep 6, 2013

Try overriding toString() method in the User class:

@Override
public String toString() {
    return this.name;
}