I'm still learning Android, I need to have a spinner and for it to display a list of string values. However, when I submit that data later on I need a corresponding integer value.
Similarly to how a HTML Select uses <option value="2">BlahBlah</option>
.
From searching I've come up with a method which works, just wondering if anyone had any suggestions for improving the code?
I've got the two variables setup:
private String[] arrMuppetNames = {"Kermit","Gonzo","Fuzzy","Animal"};
HashMap<String, Integer> hashMuppets = new HashMap<String, Integer>();
hashMuppets
is built up with a simple set of "Kermit":1,"Gonzo":2 etc.
Then to stop the code running on load I've added a "--please select--"
to index 0.
//Add "please select" to spinner
arrNewArray[0] = this.getString(R.string.muppet_select);
for(int i=0; i < arrMuppets.length; i++){
arrNewArray[i+1] = arrMuppets[i];
}
Obviously I add this array arrNewArray
to the spinner using ArrayAdapter
. Then use the OnItemSelectedListener
.
private Spinner.OnItemSelectedListener spinnerListener = new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Spinner spinner = (Spinner) findViewById(R.id.muppet_spinner);
//Arg 3 is selected index. Lets ensure we didn't select our "Please select"
if(arg3 != 0){
//Get Selected Item and convert to corresponding value using hashMap
String strSelectedMuppet = spinner.getSelectedItem().toString();
int intCatID = hashMuppets.get(strSelectedMuppet);
//Show toast of value
Toast.makeText(getApplicationContext(), String.valueOf(intCatID), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
//Do nothing
}
};
If anyone has any suggestions or pointers I'd very much appreciate it. I'm happy to post the full code if you'd like, but I'm hoping the above short example is pretty self explanatory.
Thanks