How to update a CursorAdapter tied to listview when number of items changes?
Asked Answered
R

3

6

I have a ListView backed by a custom adapter based on a CursorAdapter.

The cursor I give it is based on a list of Notes in the database (each note is a DB row).

Everything works just fine until I delete a note from the database. I'm not sure how to properly update the cursor/adapter/listview to display the new data.

I've read conflicting posts on using adapter.notifyDataSetChanged() vs cursor.requery() to refresh the UI, but neither of them seems to work in this case. The only way I've been able to refresh it is by creating a new cursor from a new query and calling adapter.changeCursor(newCursor).

Could someone demonstrate the proper way to update the backing data and then the UI (with psuedocode if possible).

Recoverable answered 16/8, 2010 at 18:33 Comment(0)
A
9

You have to requery and then notifyDataSetChanged.

Asper answered 16/8, 2010 at 19:28 Comment(1)
I think the requery model has been deprecated as of honeycomb (at least not recommended). CursorLoader is the preferred method currently.Recoverable
V
1

Calling requery will re-execute the exact query that was used to create the cursor - that is, it won't re-execute the actual method in your code. So if your method contains dynamic stuff such as sorting based on a preference, it won't be updated. In this case, you don't want to use the same query, you want a different one.

Virgo answered 16/8, 2010 at 19:48 Comment(0)
P
0

This is what works for me, im not sure its the best way.

c = db.rawQuery( "SELECT * FROM mytable", null); //same line of the first initialization
adapter.swapCursor(c);

I refresh the only cursor, I dont know what to do with a new one. Also i dont understand pepole that answer with a name of a function.

Postage answered 27/8, 2014 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.