简体   繁体   中英

onRestoreInstanceState of SimpleCursorApdater

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 .

  • chose a item on the Countries List will filter items of the Regions List by changing query condition of the RegionAdapter
  • chose a item on the Regions List will filter items of the Cities List by changing query condition of the 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().

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM