Search code examples
androidandroid-listviewandroid-arrayadaptersimpleadapter

Converting from simpleAdapter to ArrayAdapter


I have built myself an app with a list in it. Until now i have used a SimpleAdapter to populate the list, but i decided to move to an ArrayAdapter. Problem is, i can't figure how to populate the ArrayAdapter in the same way! Here is the way i used my SimpleAdapter:

adapter=new SimpleAdapter(this, listItems, R.layout.custom_row_view, new String[]{"name", "current", "reset"},  new int[] {R.id.text1, R.id.text2, R.id.text3});

My listItems variable is actually setup like this:

static final ArrayList<HashMap<String,String>> listItems = new ArrayList<HashMap<String,String>>();

Now, when trying to use the ArrayAdapter constructor with the same arguments, it give me an error. How could this be done?


Solution

  • Now, when trying to use the ArrayAdapter constructor with the same arguments, it give me an error.

    That is because an ArrayAdapter is designed for very simple scenarios where the data is in the form of a list/array with only a single widget(usually a TextView) to bind to. As you have three widgets in your layout you'll need to extend the ArrayAdapter class to bind your data as it can't do that on its own with the default implementation, something like this:

    listView.setAdapter(
                new ArrayAdapter<HashMap<String, String>>(this, R.layout.custom_row_view,
                        R.id.text1, listItems) {
    
                            @Override
                            public View getView(int position, View convertView,
                                    ViewGroup parent) {
                                View rowView = super.getView(position, convertView, parent);
                                final HashMap<String, String> item = getItem(position);
                                TextView firstText = (TextView) rowView.findViewById(R.id.text1);
                                firstText.setText(item.get("corresponding_key"));
                                TextView secondText = (TextView) rowView.findViewById(R.id.text2);
                                secondText.setText(item.get("corresponding_key"));
                                TextView thirdText = (TextView) rowView.findViewById(R.id.text3);
                                thirdText.setText(item.get("corresponding_key"));
                                return rowView;
                            }
    
                });
    

    But in the end there is the question why do you want to use ArrayAdapter, when the SimpleAdapter is more suitable for your scenario.