James Dudley
James Dudley

Reputation: 957

Creating a Spinner from an ArrayList<Object>

I am wanting to create a Spinner from an ArrayList of Objects I have created and therefore when one is selected I can go back to that ArrayList and get the rest of the information from it

Example

public class ObjectName {
    private int ID;
    private String name;
    private String name2;
    public ObjectName{int pID, String pName, String pName2) {
        ID = pID;
        name = pName;
        name2 = pName2;
    }
    //Getters Here
}

Example of Spinner Code

ArrayList<ObjectName> objects = new ArrayList<ObjectName>;
ArrayAdapter<ObjectName> adapter = new ArrayAdapter<ObjectName>(this, android.R.layout.simple_spinner_item, objects);

Of course the Spinner does not show what I want. Is there an easy way to solve this

Thanks for your time

Upvotes: 2

Views: 8742

Answers (2)

juanlugm
juanlugm

Reputation: 155

You need to implement toString in your ObjectName class as Caner said, and you will also need to set the adapter for your spinner, using something like:

((Spinner) findViewById(R.id.mySpinner)).setAdapter(adapter);

Upvotes: 0

Caner
Caner

Reputation: 59168

You need to implement toString method inside ObjectName class. Otherwise spinner cannot know what to show!

public String toString() {
    return ID + " " + name + " " + name2;
}

Upvotes: 2

Related Questions