Set Key and Value in spinner

77,538

Solution 1

Try to use HashMap to store Key-Value pair data and in your case spinner item index as key and Province_ID as value. Check below example for more details.

Prepare value for spinner

String[] spinnerArray = new String[Province_ID.size()];
HashMap<Integer,String> spinnerMap = new HashMap<Integer, String>();
for (int i = 0; i < Province_ID.size(); i++)
{
   spinnerMap.put(i,Province_ID.get(i));
   spinnerArray[i] = Province_NAME.get(i);
}

Set value to spinner

ArrayAdapter<String> adapter =new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Get value to spinner

String name = spinner.getSelectedItem().toString();
String id = spinnerMap.get(spinner.getSelectedItemPosition());

Solution 2

Better approach to populate spinner with key and value should be:

Step 1: Create POJO class which will take care of key and value

public class Country {

    private String id;
    private String name;
    
    public Country(String id, String name) {
        this.id = id;
        this.name = name;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    //to display object as a string in spinner
    @Override
    public String toString() {
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Country){
            Country c = (Country )obj;
            if(c.getName().equals(name) && c.getId()==id ) return true;
        }

        return false;
    }

}



Note: toString() method is important as it is responsible for displaying the data in spinner, you can modify toString() as per your need

Step 2: Prepare data to be loaded in spinner

 private void setData() {

        ArrayList<Country> countryList = new ArrayList<>();
        //Add countries

        countryList.add(new Country("1", "India"));
        countryList.add(new Country("2", "USA"));
        countryList.add(new Country("3", "China"));
        countryList.add(new Country("4", "UK"));

        //fill data in spinner 
        ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(context, android.R.layout.simple_spinner_dropdown_item, countryList);
        spinner_country.setAdapter(adapter);
        spinner_country.setSelection(adapter.getPosition(myItem));//Optional to set the selected item.    
    }

Step 3: and finally get selected item's key and value in onitemselected listener method of spinner

spinner_country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                 Country country = (Country) parent.getSelectedItem();
                 Toast.makeText(context, "Country ID: "+country.getId()+",  Country Name : "+country.getName(), Toast.LENGTH_SHORT).show();    
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {    
            }
        });

Solution 3

Use a LinkedHashMap and store the "strings that you want to display in the spinner" as the keys and the object that you would like to retrieve based on the spinner selection as the values . For eg. , for some reason you have a Float datatype associated with the spinner items , use:

LinkedHashMap<String , Float> aMap = new LinkedHashMap<>(10);

Then for the spinner , we can set the values as :

    ArrayList<String> values = new ArrayList<>(aMap.keySet());
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,values);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

Finally , in the OnItemSelectedListener , retrieve the float value as:

 @Override
 public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                aMap.get(adapterView.getItemAtPosition(i));
                
            }
Share:
77,538

Related videos on Youtube

Nima.S-H
Author by

Nima.S-H

Updated on July 09, 2022

Comments

  • Nima.S-H
    Nima.S-H almost 2 years

    I have a spiner and I want set a key and a value on this,I use of HashMap,It's work,but show one row,like this:

    enter image description here

    Code:

            final View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
    
        Spinner spin=(Spinner)rootView.findViewById(R.id.spinner1);
    
        HashMap<Integer, String> P_Hash=new HashMap<Integer, String>();
    
        Update Get_Information=new Update(rootView.getContext());
    
        ArrayList<String> Province_NAME=new ArrayList<String>();
        Province_NAME=Get_Information.GET_Province();
    
        ArrayList<Integer> Province_ID=new ArrayList<Integer>();
        Province_ID=Get_Information.Get_Province_ID();
    
        for (int i = 0; i < Province_ID.size(); i++)
        {
            P_Hash.put(Province_ID.get(i), Province_NAME.get(i));
            Log.d("Province_ID.get(i)", Province_ID.get(i)+"");
            Log.d(" Province_NAME.get(i)",  Province_NAME.get(i)+"");
        }
    
    
        ArrayAdapter<HashMap<Integer, String>> adapter = new ArrayAdapter<HashMap<Integer,String>>(rootView.getContext(), android.R.layout.simple_spinner_item);
        adapter.add(P_Hash);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    
        spin.setAdapter(adapter);
    
  • Janpan
    Janpan over 9 years
    @HareshChhelana , thank you for the great example. For the spinnerArray, province_NAME and province_ID , I used arraylists as it made some of the object handling easier, so instead of spinnerArray[i] = ... I just have spinnerArray.add(provinceName.get(i)); This may help with some index out of bounds issues. In any case, thx for the great solution !
  • medskill
    medskill over 7 years
    @HareshChhelana i'm not sure but does hashmap preserves insertion order ? (i remember there are some issues with hashmap and random order).
  • Haresh Chhelana
    Haresh Chhelana over 7 years
    @medskill, As per changes i have store index as key and id as value so it will resolve problem for same name in spinner item.
  • Mitro
    Mitro over 7 years
    To keep the order of the inserted elements you should use LinkedHashMap
  • Jayanta
    Jayanta almost 7 years
    @SrinivasGuni sir great example. sir i need help, can you explain why override onItemSelected method. i try without override but not worked. so can you solve my problem
  • Srinivas Guni
    Srinivas Guni almost 7 years
    @jayanta first of all good question We are using arrayadapter which act as an bridge between dataset(our countries list) and adapterview i.e spinner's each row. So whenever you want click listener to work for each row selection you must override onitemselected listener of Adapterview interface So everytime you click row of spinner this method will be called and you can do whatever you want on click of that row.Hope it will helps
  • L.Grillo
    L.Grillo over 5 years
    there's no need to create a second array spinnerArray, just use spinnerMap.values():
  • Dika
    Dika about 5 years
    you should emphasize "toString()" method part, man. it is the key. I edited your explanation, and I hope someone accept my edit
  • Srinivas Guni
    Srinivas Guni about 5 years
    @Dika I have already did that you can see Note section. May be you skipped that part.
  • RRGT19
    RRGT19 about 5 years
    @SrinivasGuni Why do you Override the equals method inside the POJO? It's to be able to set a selection in spinner? Could you add an explanation above the equals method telling why you are overriding it?
  • Srinivas Guni
    Srinivas Guni about 5 years
    @RRGT19 Equals method helps to compare object of same type so that no duplicate record added in arraylist. You can skip the equals method.