Question

I am deleting an element from an adapter, and the element is supposed to be deleted and in the UI, and ListView refreshed. What happens is that the element is indeed being deleted from the Adapter, but stays in the List still, until the list is manually refreshed(open another fragment and then back to the List fragment and boom! the deleted element is indeed not anymore in the list). But I want the list to be refreshed right away!

Here is what I am using for deletion:

                    ClockAdapter myAdapter = (ClockAdapter)listView.getAdapter();
                    Alarm myAlarm = myAdapter.getItem(selectedPosition);
                    MyAlarmManager.deleteAlarm(myAlarm);
                    myAdapter.notifyDataSetChanged();

Will appreciate any help!

Was it helpful?

Solution

You need to remove the item from the Adapter as well. Call:

ClockAdapter myAdapter = (ClockAdapter)listView.getAdapter();    
//...
Alarm myAlarm = myAdapter.getItem(selectedPosition);
myAdapter.remove(myAlarm);
myAdapter.notifyDataSetChanged(); 

OTHER TIPS

notifyDataSetChanged () - doc says,

Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

Hence, calling this tells the adapter that the data passed to it (a list of alarm in your case) has been modified so it should refresh. Which means your adapter will again read and load data from the data-structure you have attached to it.

So for the adapter to reflect the deletion, you must delete it from that list as well.

Say, you have a ArrayList<Alarm> called myArrayAlarm attached to your adapter, then you should delete it from this.

You can call,

myArrayAlarm.remove(myAlarm)
myAdapter.notifyDataSetChanged();

Philipp's way is also correct. :)

after removing items always add the below two lines

            notifyDataSetChanged();
            notifyDataSetInvalidated();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top