Reputation: 2612
How to save/restore state of ListView
which attached to a CursorAdapter
? Example:
I have a Android Activity
with 3 ListView
: Countries, Regions, Cities.
They are attached to 3 SimpleCursorApdater
: CountryAdapter
, RegionAdapter
, CityAdapter
.
RegionAdapter
CityAdapter
Pseudo code:
void countryList_onItemSelected() {
regionsAdapter.getFilter().filter(countryId);
}
void regionList_onItemSelected() {
cityAdapter.getFilter().filter(regionId);
}
Cursor regionAdapter_FilterQueryProvider_runQuery(countryId) {
Cursor cur = dbHelper.getReadableDatabase().
query("Select * from Region where countryId = "+countryId);
return cur;
}
Cursor cityAdapter_FilterQueryProvider_runQuery(regionId) {
Cursor cur = dbHelper.getReadableDatabase().
query("select * from City where regionId = "+regionId);
return cur;
}
When the onRestoreInstanceState()
is called, the cityListView
is empty because the 2 runQuery()
methods have not been terminated yet. So I cannot go straight:
void onRestoreInstanceState(Bundle state) {
...
savedCitySelection = state.getInt("citySelectedItemPosition")
cityListView.setSelection(savedCitySelection); // <= NOOO! the cityListView is empty
}
Question:
How can I save/restore the state of these 3 lists with onSaveInstanceState()
and onRestoreInstanceState().
Upvotes: 1
Views: 408
Reputation: 3836
I'd suggest using a Loader
.
Then when the loading is finished and you swap the cursor in you can call smoothScrollToPosition(int position)
* on the ListView
.
CommonsWare has a good CursorLoader based on the support library here:
https://github.com/commonsguy/cwac-loaderex
*(Note: smoothScrollToPosition requires Android 2.2)
Upvotes: 1