Question

I want to populate a spinner in my android application, Is there a default adapter that can deal with a key and a value? Because the ArrayAdapter only stores one value per item?

I want my spinner to have the following:

1 dog 2 cat 3 mouse

But it must only display the value, but when I submit my input I want to be able to get the id / key?

Was it helpful?

Solution

Create a pojo class

public class SpinnerUtils {
     public SpinnerUtils(String spinnerText, int value) {
         this.spinnerText = spinnerText;
         this.value = value;
     }

     public String getSpinnerText() {
         return spinnerText;
     }

     public int getValue() {
         return value;
     }

     public String toString() {
         return spinnerText;
     }

     String spinnerText;
     int value;
 }

Then

 SpinnerUtils items[]=new SpinnerUtils[array.length()];
    items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));   

    for (int i = 0; i <array.length(); i++) {

items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));                       
                }


         ArrayAdapter<SpinnerUtils> adapter = new ArrayAdapter<SpinnerUtils>(this,android.R.layout.simple_spinner_item, items);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                s.setAdapter(adapter);

where s is your spinner. To retrieve the id:

 SpinnerUtils d = items[position];
             int   standard = d.getValue(); 

Create the above 2 lines within the setOnItemSelectedListener of the spinner to get the id.I have given you a rough idea.Hope it will work.

OTHER TIPS

Your ArrayAdapter can contain one value, true, but this value can be an anything ;)

new ArrayAdapter<String>()
new ArrayAdapter<MyObject>()
ArrayList<HashMap<String,String>>()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top