Question

When you create a custom adapter extending ArrayAdapter<T>, it has usually the form:

public class ListAdapter extends ArrayAdapter<Item> {

    private List<Item> mData;

    public ListAdapter(Context context, int resource, List<Item> data) {
        super(context, resource, data);
        mData = data;
    }
}

The data is initially saved in a private member mData, but also the ArrayAdapter saves the data in its own member mObjects. I am pretty sure those are not actual copies, but references to the same list.
Now, and this is my question, if during the ListView processing, for some reason, you have to replace your own list with a fresh new List, I think you should also do:

mData = new List<Item>();
super.clear();
super.addAll(mData);

otherwise there will be no consistency in ListView, and methods like getFilter().filter() will not work.

Am I correct?

Was it helpful?

Solution

I think, when you say mData = data; it only copies pointer of the data array, because when you execute that;

ListAdapter adapter = new ListAdapter(context, resource, data);
data.clear();
adapter.notifyDataSetChanged();

it changes list. So it keeps pointer of your source array,

Second, I think (not sure) you cannot use filter function of adapter, at least I couldn't use and write my own filter function. I filter elements from sqlite(I take my elements from database). and use notifyDataSetChanged function of adapter.

OTHER TIPS

You are right. Your ListAdapter doesn't make a deep copy of the provided list of Items. This means that changing an Item instance 'outside' the ListAdapter will put the ListAdapter in an invalid state.

However, you can 'fix' this by calling notifyDataSetChanged on the ListAdapter.

List<Item> itemList = ....
....
....
ListAdapter adapter = new ListAdapter(this, R.layout.somelayout, itemList);
....

Now, if you change an item 'outside' the ListAdapter, you can still make your ListAdapter be in sync with the change:

itemList.get(idx).changeSomethingInItem("Hello"); // Changes the Item at index 'idx'.
adapter.notifyDataSetChanged();                   // Notify adapter about this change.

you really needn't pretty sure whether it actual copies or not ,just extend BaseAdapter

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