16

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:

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Joy
  • 1,707
  • 7
  • 29
  • 44
  • U r question is messed up make it more clear what u want to do and what is u r problem – Developer Sep 06 '13 at 12:13
  • 1
    Here it's the memory adress of the object that you are displaying. you probably did something like an arraylist of your object. Instead of a list of object you should create a list of String from your list of object and give it to the spinner. you can create a Hashmap to get the good one when you select an item of the spinner – An-droid Sep 06 '13 at 12:20
  • @Gaurav no need for that cause someone already understood and gave me the right answer :) – Joy Sep 06 '13 at 12:22

2 Answers2

41

Try overriding toString() method in the User class:

@Override
public String toString() {
    return this.name;
}
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • 4
    As an addition, if you're trying to get the `User` object to save it later or whatever, you can use the following: `User user = (User) ( (Spinner) findViewById(R.id.user) ).getSelectedItem();` – Joshua Pinter Jan 16 '14 at 17:37
  • What about a case which I have an object with three fields, Id, and field to be shown in the drop down list "to override toString method" and field just to show it when select this object as a selected filed ? Can we achieve this ? – user1510006 Dec 17 '15 at 14:32
0

check the method public View getDropDownView(int position, View view, ViewGroup parent);

you will not need to override the toString() method of the object.

@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
    view = inflter.inflate(R.layout.obino_spinner_style, null);
    TextView goalNameTV= (TextView)view.findViewById(R.id.ObiNoID_Spinner_Text);
    goalNameTV.setText(goalItemList.get(position).getGoalType());
    return view;
}
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60