Reputation: 593
I have a simple Spinner
implemented as:
vehicle = json.getJSONArray("vehicle");
for(int i = 0; i < vehicle.length(); i++){
JSONObject c = vehicle.getJSONObject(i);
//put json obkject on variable
String id = c.getString("id");
String name = c.getString("name");
String capacity = c.getString("capacity");
String cost = c.getString("cost");
String v = name + " ("+capacity + " Liters)";
vehicleList.add(v);
// Set Spinner Adapter
mySpinner.setAdapter(new ArrayAdapter<String>(OrderDetails.this,android.R.layout.simple_spinner_dropdown_item,vehicleList));
// Spinner on item click listener
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
car = vehicleList.get(+position);
Toast.makeText(getApplicationContext(), car, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
car = null;
}
});
}
I wanted to grab the value of "ID" in the car variable. Is it possible with above implementation?
Thanks in advance.
Upvotes: 1
Views: 1322
Reputation: 2687
try to replace your item click listener with this ...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
int spinnerItem = spinner.getSelectedItemPosition();
car = vehicleList.get(spinnerItem);
Toast.makeText(getApplicationContext(), selectedId, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do here :|
}
});
//EDIT you can create another list that hold values of IDs ... and then add values to it as vehicleList ...
idList.add(id);
and then just call when item is selected in spinner
String selectedId = idList.get(spinnerItem);
Upvotes: 1
Reputation: 2927
Returns the position selected.
mySpinner.getSelectedItem()
or
mySpinner.getSelectedItemPosition()
Upvotes: 0