Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating Android Spinner with List of Objects

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:

like image 698
Joy Avatar asked Sep 06 '13 12:09

Joy


People also ask

How can I tell if spinner is clicked or not in android?

Let the Spinner's first value be something like "-please select-". when the user clicks on the next button perform validation and check whether the value of the selectedItem in the spinner is "-please select-" and if yes, then display a toast and ask the the user to select something from the spinner.

What is the use of adapter object in Android SDK explain ArrayAdapter in detail?

You can use this adapter to provide views for an AdapterView , Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner .


1 Answers

Try overriding toString() method in the User class:

@Override
public String toString() {
    return this.name;
}
like image 168
Szymon Avatar answered Sep 28 '22 05:09

Szymon