Spinner with Key-Value Pair

android spinner key-value xml
android spinner with id and value
android spinner values
how to set value in spinner dynamically in android
how to display selected value in spinner in android
key and value
spinner setonitemselectedlistener
set value to spinner

I am working on multi languages UI. My requirement is in spinner I want to show data in Hindi but when it will be selected it should return english show it can compare to further decision making. Just like tag with tag.

My java code is something like this

    HashMap<String,String> options=new HashMap<String,String>();
    String optionsEnglish [] = getResources().getStringArray(R.array.option_array);
    String optinsHindi[]= getResources().getStringArray(R.array.option_array_hindi);

    for(int i=0;i<optionsEnglish.length;i++)
    {
        options.put(optionsEnglish[i], optinsHindi[i]);
    }
    Spinner optionSpinner = (Spinner) findViewById(R.id.optionPicker);


    ArrayAdapter<HashMap<String, String>> dataAdapter = new ArrayAdapter<HashMap<String,String>>(this, android.R.layout.simple_spinner_item);
    dataAdapter.add(options);


    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    optionSpinner.setAdapter(dataAdapter);

In xml

    <resource>       
            <string-array name="option_array">
                  <item>Market</item>
                  <item>Commodity</item>
            </string-array>

            <string-array name="option_array_hindi">
                  <item>बाजार</item>
                  <item>वस्तु</item>


            </string-array>

     </resources>

Hope this can help you

Add Data in in Spinner

private void setDataInSpinner(Spinner id, int dataArray) {
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, dataArray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        id.setAdapter(adapter);
    }

To get the selected value of Spinner use this

Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
String Text = mySpinner.getSelectedItem().toString();

Or You can use setOnItemSelectedListener to get the selected values

String value = GetClassCode.getCode(Text);//here u have to pass the value that is selected on the spinner

Create a Class

public class GetClassCode {
    static HashMap<String, String> codeHash = new HashMap<String, String>();

    static {
        init();
    }

    public static void init() {
        codeHash.put("key", "value");
        codeHash.put("key", "value");
        codeHash.put("key", "value");
        codeHash.put("key", "value");

    }

    public static String getCode(String param) {
        return codeHash.get(param);
    }
}

Best practice to implement key-value pair in android Spinner, setup Spinner: spLang = (Spinner)view.findViewById( R.id.spLang ); spLang.​setOnItemSelectedListener( this ); ArrayList<String> sp_Lang = new  It's using the toString method of HashMap to display the value. So it sees this as one object being in the spinner. There are two ways to do this: Implement an extension to ArrayAdapter and override the getView() method to return the appropriate value. Implement your own Object to fill the spinner and override its toString method.

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;
    }

  }

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);
        sp_country.setAdapter(adapter);
        sp_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

sp_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) {    
            }
        });

Spinner with Key-Value Pair, Spinner with Key-Value Pair - android. setAdapter(adapter); } To get the selected value of Spinner use this Spinner mySpinner  Create a map of key-values, and take a value in onItemSelected (you can obtain "key" via spinner.getAdapter ().getItem (position)).

You made two separate string array for language words like in given xml ,right? then just use ArrayAdapter for first option array and set adapter in spinner. and on select of any item of spinner according to it's position fetch world from second string array..

it will be quite easy and also work for more then 2 languages.

Add hashmap key value to spinner · GitHub, Here is my example from sqlite to spinner key/value. List<String> ID; List<String> Name; protected override void OnCreate(Bundle  Spinner Using Key/Value Pairs Often it is necessary to use Spinner to display key values that are associated with some kind of data used by your app. Because Spinner does not work directly with key/value pairs, you must store the key/value pair separately, populate the Spinner with key values, then use the position of the selected key in the Spinner to look up the associated data value.

I created an HashMap adapter that might help. Also see example project here

    mapData = new LinkedHashMap<String, String>();

    mapData.put("shamu", "Nexus 6");
    mapData.put("fugu", "Nexus Player");
    mapData.put("volantisg", "Nexus 9 (LTE)");
    mapData.put("volantis", "Nexus 9 (Wi-Fi)");
    mapData.put("hammerhead", "Nexus 5 (GSM/LTE)");
    mapData.put("razor", "Nexus 7 [2013] (Wi-Fi)");
    mapData.put("razorg", "Nexus 7 [2013] (Mobile)");
    mapData.put("mantaray", "Nexus 10");
    mapData.put("occam", "Nexus 4");
    mapData.put("nakasi", "Nexus 7 (Wi-Fi)");
    mapData.put("nakasig", "Nexus 7 (Mobile)");
    mapData.put("tungsten", "Nexus Q");

    adapter = new LinkedHashMapAdapter<String, String>(this, android.R.layout.simple_spinner_item, mapData);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner = (Spinner) findViewById(R.id.spinner);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

How populate a Spinner with Key/Value, void setSpinner(String value) { int position = getSpinnerField(). Sort a Map<Key​, Value> by values A Java collection of value pairs? (tuples  Spinner mySpinner = (Spinner)findViewById(R.id.spinner); String Text = mySpinner.getSelectedItem().toString(); Or You can use setOnItemSelectedListener to get the selected values String value = GetClassCode.getCode(Text);//here u have to pass the value that is selected on the spinner

A bit old question, but this is in the top answers when searching from google.

I used this method:

Get the localized value from the spinner:

String localizedValue = ((Spinner) findViewById(R.id.mySpinner)).getSelectedItem().toString();    

Then get the key dynamically from string resources file:

String key = (String) getResources().getText(getResources().getIdentifier(localizedValue, "string", "my.package.name"));    

All languages should contain the key for the localizedValue in strings.xml:

बाजार=Market

Setting selected item of Spinner by value rather than by position , Custom Spinner with key value pair Requirement. if developer want to select item by ID not by Index of spinner. if developer want to get  Greetings with Android Populate Spinner From JSON Array and Web Service Tutorial Example. You will learn how to populate an android spinner using a json web service and MySQL Database in this post. To display json data in spinner in android, we need to create string arraylist using web service.

Custom Spinner with Key Value, I've been looking for samples on using a Key Value pair on a Spinner but I couldn​'t find any. Of-course after I spent hours coming up with my  Because Spinner does not work directly with key/value pairs, you must store the key/value pair separately, populate the Spinner with key values, then use the position of the selected key in the Spinner to look up the associated data value. Aşağıdaki örnek değişkenini MainActivity sınıfına ekleyin.

Key Value Pair Data for Spinner (Android), I created enum to for the id/key. enum class Position { TOP, BOTTOM }. Create adapter for spinner.

Android Spinner With Key Value Object Adapter (Kotlin), Because Spinner does not work directly with key/value pairs, you must store the key/value pair separately, populate the Spinner with key values 

Comments
  • so what is u r problem ??
  • I am not getting drop-down of two option बाजार, वस्तु instead of i am getting {Market-बाजार, Commodity-वस्तु} printed as only one option
  • i want two option with lable बाजार, वस्तु and when बाजार will be selected market should return and when वस्तु selected commodity should return so i can make proper decision for the some action on itemSelected event
  • see as i know this feature of key /value is not available in Android .so for the same i have implemented the code that i have posted use that code might help u.because me to have the same requirement i have done like this
  • Why can't you set the text in spinner's onItemSelected() method.?
  • I am not getting how to add it to spinner can us give me the complete code
  • see on the selection of the spinner get the data pass to the function GetClassCode in that codeHash hash set the key as बाजार and value as Market so when he will select the बाजार this class will return Market it very simple
  • have u got or still any issue
  • Thank you for the answer. From your code the getCode(param) will return null only because for a hashMap get(param) method returns the value of a hashmap provided the param is key. So for getting the key the method should be public static String getCode(String param) { for (String keyVlue : codeHash.keySet()) { if (codeHash.get(keyVlue).equals(param)) { return keyVlue; } } return null; }
  • but its show a whole array on dropdown like this : DepartmentSel(id=5, name=DepartmenName)