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 ArrayList<String>();
sp_Lang.add("english");
sp_Lang.add("french");
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sp_Lang);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spLang.setAdapter(spinnerAdapter);
For Perticular Spinner item Selection:
int Position = spinnerAdapter.getPosition("Japanese");
spLang.setSelection(Position);
First Create Hashmap for store Key and value pair
HashMap<String ,String> hmLang = new HashMap<String,String>();
Now Add value like this into HashMap :
hmLang.put("english" ,"en");
Here in HashMap key = YourValue and Value = yourKey
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
switch(adapterView.getId())
{
case R.id.spLang:
String lang_Name = adapterView.getItemAtPosition(position).toString();
String lang_Key = hmLang.get(lang_Name);
break
}
If you have any issue with this code then please ask
Set Key and Value in spinner
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());
spinner key and value
I would go for map instead.
1-create the languages map
Map<String, String> languages = new HashMap<>();
languages.put("hindi", "hi");
languages.put("arabic", "ar");
languages.put("english", "en");
2-get the selected item
String selectedLanguage = mySpinner.getSelectedItem().toString();
String languageToSend=languages.get(selectedLanguage); //send it to url
Spinner with Key-Value Pair
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);
}
}
What's the correct way to implement key-value pair in Spinner in android
this is one way.
i use it quite a lot though i use my own adapter (inheriting from BaseAdpater).
Another way would b like the above to have an index (0,1,2 etc ) mappd to a value and when you get an item get it's index a well so you can retrieve it's value fro mthe map.
I like that option less...
How to set key value to spinner list from firebase
You're listening one level too high in your JSON tree. Your onDataChange()
is now triggered with the CIVIL
node, while you likely want it one level lower.
rootRef.child("First/CIVIL").addValueEventListener(
One thing to note though: this will load all data under each date, just to show that date in the spinner. If that is a significant amount of data, you're wasting your user's bandwidth.
I'd consider in that case flattening your data structure and keeping a separate node with just the dates:
"Dates": {
"CIVIL": {
"2015-16": true,
"2016-17": true,
"2017-18": true
}
}
The true
values are just needed to make sure Firebase doesn't delete the keys. Downloading this branch of the JSON ensures you only download the minimum data that is needed to populate the spinner.
How to Implement Spinner with key-value in Android?
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.
The first method has preference, because it allows for much more flexibility.
How to set spinner selection if every field has key and value pair
There is a simply, magic way to display custom object model in spinner
public class TruckCapacity {
...
@Override
public String toString() {
return whateverYouWantToDisplay;
}
}
And a way to get selected item
TruckCapacity truckCapacity = (TruckCapacity) parent.getItemAtPosition(position);
@Edit
You can for example search your spinners list to find searched id, loop iteration is an equivalent of your array position, and then programitically set selection
public int findSpinnerPosition(List<TruckCapacity> truckCapacityList, int searchId) {
int position = -1;
for (int i = 0; i < truckCapacityList.size(); i++) {
if (truckCapacityList.get(i).getId() == searchId) {
position = i;
break;
}
}
return position;
}
And select
int position = findSpinnerPosition(truckCapacityList, 7);
if (position != -1) {
truckCapacitySpinner.setSelection();
} else {
//item with this id doesn't exist
}
Android setting default value from Hashmap Key for Spinner in Simple Adapter
Create a model class for your JSON
data,
private class Item {
String key;
String value;
public Item(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
Parse your data into this model class,
List<Item> list = new ArrayList<>();
Iterator<String> iterator = jsonObject1.keys();
while (iterator.hasNext()) {
String id = iterator.next();
String name = jsonObject1.getString(id);
list.add(new Item(id, name));
}
Initialize the Spinner
,
final ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_spinner_dropdown_item, list);
category.setAdapter(adapter);
Find the index of your get_selected_item_id
in the list
and use setSelection
method of Spinner
to set it as default.
int index = findIndexOf(list, get_selected_item_id);
if (index != -1) {
category.setSelection(index);
}
The findIndexOf
method,
private int findIndexOf(List<Item> list, int selectedKey) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getKey().equals(String.valueOf(selectedKey))) {
return i;
}
}
return -1;
}
The ItemSelectedListener
,
category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
// get selected item using position argument
Item selectedItem = list.get(position);
// your code
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Related Topics
Disable Default Animation from Portrait to Landscape
Edittext Seterror() with Icon But Without Popup Message
How to Display a Route Between Two Geocoords in Google Maps
Connecting to Wifi Using Adb Shell
Hide Ics Back Home Task Switcher Buttons
How to Set Shadow to a View in Android
Phonegap Eclipse Issue - Eglcodeccommon Glutilsparamsize: Unknow Param Errors
Android Layout Folders: Layout, Layout-Port, Layout-Land
How to Get the Position Selected in a Recyclerview
Viewpager Detect When User Is Trying to Swipe Out of Bounds
How to Get Data from Service to Activity
Android Slidingdrawer from Top
How to Set the Language in Speech Recognition on Android
Android:Fill Spinner from Java Code Programmatically
What Causes Android's Contentresolver.Query() to Return Null