lulu
lulu

Reputation: 271

ListView not updating after item deletion

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!

Upvotes: 2

Views: 1991

Answers (3)

Mehroz Munir
Mehroz Munir

Reputation: 2356

after removing items always add the below two lines

            notifyDataSetChanged();
            notifyDataSetInvalidated();

Upvotes: 0

Atul O Holic
Atul O Holic

Reputation: 6792

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. :)

Upvotes: 1

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

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(); 

Upvotes: 4

Related Questions