@Haresh Chhelana example is good, However if you want to show both name and code in spinner after selecting, check this out.
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
mapData = new HashMap<String, String>();
mapData.put("name", json.getString("Name"));
mapData.put("code", json.getString("Code"));
items.add(mapData);
}
SimpleAdapter adapter = new SimpleAdapter(this, items, android.R.layout.simple_list_item_2, new String[] {
"name", "code" }, new int[] { android.R.id.text1, android.R.id.text2 });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
And Spinner selected item callback
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Map<String, String> selectedItem = (Map<String, String>) parent.getSelectedItem();
String name=selectedItem.get("name");
String code=selectedItem.get("code");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
5
solved Set value for Spinner with custom Adapter in Android