Search code examples
androidsaverestoresimplecursoradapterandroid-cursoradapter

Android Save and Restore List State with CursorAdapter


I have a list view in a fragment that is populated by a CursorAdapter.

When the device rotates I want to save the state of the list, then restore it without having to make another call to the SQLite DB.

How do I do this?

I'm not using a ContentProvider or any CursorLoaders.


Solution

  • You could save your Cursor in the method onRetainNonConfigurationInstance() of your Activity or use a data fragment that holds the Cursor and call setReatinInstance() within the fragment's onCreate() method.

    You then have to recreate the CursorAdapter within the onCreate() method.

    Finally you have to store the currently visible topmost item of your ListView by calling getFirstVisiblePosition() on your ListView. This method returns an int value which you can store in a Bundle within the onSaveInstanceState() method of your Activity.

    You use this value in the onCreate() method (it's part of the bundle passed to onCreate()). And after the adapter has been set, you call [setSelectionFromTop(yourValue, 0)](https://developer.android.com/reference/android/widget/ListView.html#setSelectionFromTop(int, int)).