Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update SimpleCursorAdapter while maintaining scroll position in ListView

My problem: My ListView resets its scroll position to the top whenever I update its contents through its (customized) SimpleCursorAdapter. I would like the ListView to maintain its scroll position when updated.

I started out by creating a new adapter instance every time and using ListView.setAdapter(), but according to this discussion I should be updating the adapter instead of resetting it. I can't find a way to do this for SimpleCursorAdapter that works correctly.

Here are some things I've tried, omitting the method arguments:
- SimpleCursorAdapter.changeCursorAndColumns() with a fresh cursor successfully updates the adapter but still resets the scroll position.
- SimpleCursorAdapter.changeCursor() acts the same way.
- SimpleCursorAdapter.swapCursor() isn't available until api 11, and I am developing for api 8.
- SimpleCursorAdapter.notifyDataSetChanged() does not update the ListView. (Maybe there is another step I'm missing.)
- ListView.invalidate() does not update the ListView.
- SimpleCursorAdapter.requery() makes the ListView blank, and is deprecated.
- I'm familiar with the ListView.setSelection() solution, but I don't want my ListView to move at all when it is updated. This snaps it to a position in the list.

This seems like it should be a common and simple problem. Has anybody dealt with it?

like image 863
pvans Avatar asked Feb 13 '12 05:02

pvans


1 Answers

I've had a similar problem: My CursorAdapter reset the scroll position whenever the contents of the cursor changed.

I didn't realize that I actually did set a new list adapter each time the data changed. I thought the cursor himself would notify the adapter about changes to it's content but in my case it is the ContentProvider that triggers LoaderManager.LoaderCallbacks.onLoadFinished() in my ListFragment. In that callback I now use CursorAdapter.changeCursor() instead of creating a new adapter and everything works just fine.

I hope this helps solving your problem.

like image 186
Oderik Avatar answered Nov 15 '22 19:11

Oderik