简体   繁体   中英

Passing List of Objects (referenced) to BaseAdapter extended Class and call notifyDataSetChanged() not Working after changing reference

I am doing this for the understanding. In my case I have a class extended by BaseAdapter . in the new class I am passing the list of objects I want to bind to the ListView in android and I keep a reference to that passing list of objects.

ListView list2 = (ListView)findViewById(R.id.attachmentList);
    list2.setAdapter(new LazyAdapter(BaseAdapterExtention.this,getApplication().getInteraction().getList() ));

Like above I keep the data that I am passing as a singleton getApplication().getInteraction().getList() which I call this to get the data.

Each list item has a button, and each list item button has a click listener, when a button is clicked, I am deleting that item and repopulate the data set in the singleton object as below

getApplication().getInteraction().setList(listofObjects) .

to do that I am calling an async task and I am passing this adapter

new ListAsync(activity,BaseAdapterExtention.this).execute();

and in onPostExecute() I call the adapter.notifyDataSetChanged() . but the adapter object list is the same, the deletion is not reflected in that list and so, the list view is the same.

What's wrong I am doing?

Just call adapter.clear() before calling adapter.notifyDataSetChanged() .

By doing adapter.clear() it removes all elements from the adapter and then by using adapter.notifyDataSetChanged() it notifies the attached observers that the underlying data has been changed and any View reflecting the data set will update now without any problem.

Edit

As you are extending BaseAdapter , .clear() won't work.Hence you could call list2.setAdapter() again and pass null like this:

list2.setAdapter(null);
adapter.notifyDataSetChanged();

I added a public method in the Activity that has the ListView and there,

public void notifyDataChangeInAdapter(){
        list2.setAdapter(new BaseAdapterExtention(ExampleActivity.this, getApplication().getInteraction().getList() ));
}

I am calling this method in onPostExecute() method by using the activity reference that I passed to that asynctask constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM