Question

I have asked myself the above question and did not come to a real solution so far.

Below you can see two implementations of a custom adapter for a ListView holding Strings. The first implementation uses an additional list of values inside the Adapter, like it is also done in many ListView tutorials I have seen. (e.g. vogella-listview-tutorial)

public class CustomAdapter extends ArrayAdapter<String> {

    private ArrayList<String> mList;

    public CustomAdapter(Context context, List< String > objects) {
        super(context, 0, objects);
        mList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        String item = mList.get(position);

        // ... do stuff ...

        return convertView;
    }
}

The second implementation below simply uses the List of Strings that has already been handed to the Adapter, and does not need an additional List. Instead, the Adapters getItem(int pos) method is used:

public class CustomAdapter extends ArrayAdapter<String> {

    public CustomAdapter(Context context, List< String > objects) {
        super(context, 0, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        String item = getItem(position);

        // ... do stuff ...

        return convertView;
    }
}

Now my question:

What is the reason for using an additional List inside a CustomAdapter when you can simply use the adapters getItem(int pos) method and spare the additional List?

Was it helpful?

Solution

since you are extending ArrayAdapter that extends BaseAdapter you do not need to have a copy of the dataset, but providing it to the super is enough. If you extends another adapter, BaseAdapter you have to override

  1. getCount()
  2. getItem(int)
  3. getView(int position, View convertView, ViewGroup parent)
  4. getItemId(int)

all of the require to access to the dataset.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top