Using SimpleAdapter with Spinner

Chromium picture Chromium · Dec 8, 2010 · Viewed 10.9k times · Source

I am new to Android development. I am trying to populate a spinner by using the SimpleAdapter. But spinner's list is showing blank element. When I click any element, its text is shown properly in Toast. Please tell me what is the problem in my code below.

 public void onCreate(Bundle savedInstanceState) {

  private List<Map<String, String>> data = new ArrayList<Map<String, String>>();

  String[] from = new String[] { "colorsData" };
  int[] to = new int[] { R.id.spinner };

  String[] colors = getResources().getStringArray(R.array.colorsData);

  for (int i = 0; i < colors.length; i++) {
   data.add(addData(colors[i]));
  }

  Spinner spinner = (Spinner) findViewById(R.id.spinner);

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, android.R.layout.simple_spinner_item, from, to);
  simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner.setAdapter(simpleAdapter);

  spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
   @Override
   public void onItemSelected(AdapterView<?> parent, View view,
     int position, long id) {
    Toast.makeText(
      parent.getContext(),
      "Selected Color:-  "
        + parent.getItemAtPosition(position),
      Toast.LENGTH_LONG).show();
   }
  });
 }

 private Map<String, String> addData(String colorName) {
  Map<String, String> mapList = new HashMap<String, String>();
  mapList.put("colorsData", colorName);
  return mapList;
 }

Answer

Dan Breslau picture Dan Breslau · Dec 8, 2010

I'm about 95% sure that your to array should be declared as:

  int[] to = new int[] { android.R.id.text1 };

Give that a try.


EDIT (based on comments below):

It seems there was a bug in older versions of AndroidOS which caused that IllegalStateException. (I didn't see the exception in 2.2, but I did see it in 1.5 in the emulator.) The bug can be worked around by adding a ViewBinder to the SimpleAdapter. ViewBinder isn't hard to implement; here's an example:

    SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {

        public boolean setViewValue(View view, Object data,
                String textRepresentation) {
            // We configured the SimpleAdapter to create TextViews (see
            // the 'to' array), so this cast should be safe:
            TextView textView = (TextView) view;
            textView.setText(textRepresentation);
            return true;
        }
    };
    simpleAdapter.setViewBinder(viewBinder);

I blogged about this here.