I have a fragment with a multi-choice list. I am trying to save instance of the items that are checked in the list currently and restore them in case of app minimization and such.
Steps of testing:
- Reach the multi-choice list fragment.
- Check a few list items
- Press the home key to minimize the app.
- Press the multitasking button and choose my app to restore it
Following is the code that i am using:
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, listToShow);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mSelectedItems.clear();
int count = categoryList.getCheckedItemCount();
SparseBooleanArray booleanArray = categoryList.getCheckedItemPositions();
for (int i = 0; i < count; i++) {
mSelectedItems.add(booleanArray.keyAt(i));
}
}
});
@Override
public void onSaveInstanceState(Bundle outState) {
Log.d("SubcategoryselectionList", "onsavedinstancestate");
outState.putIntegerArrayList(SELECTED_ITEM, mSelectedItems);
super.onSaveInstanceState(outState);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
Log.d("SubcategoryselectionList", "onViewStateRestored");
if (savedInstanceState != null) {
if (savedInstanceState.getIntegerArrayList(SELECTED_ITEM) != null) {
Log.d("SubcategoryselectionList", "onViewStateREstored selected items found");
mSelectedItems = savedInstanceState
.getIntegerArrayList(SELECTED_ITEM);
for (int i = 0; i < mSelectedItems.size(); i++) {
categoryList.setItemChecked(mSelectedItems.get(i), true);
}
}
}
super.onViewStateRestored(savedInstanceState);
}
And when I see the logs, the method onViewStateRestored
is never called.
To counter this I thought of using the activity lifecycle and use its method onRestoreInstanceState()
to achieve the above mentioned effect but surprisingly I cant see the logs that I added to this method.
Please someone help in clarifying how the lifecycle of the Activity and Fragment working in this case and how can I restore my state in the best possible manner.
onViewStateRestored will be called when android system itself destroys your fragment before your try to relaunch it. Since your fragment is still alive while it is in the background(after your tapped home key), hence relaunching your application (from multitasking key) will not result in calling onViewStateRestored() method.
In order to see this method in action, try rotating your device(portrait -> landscape or vice-versa) you will be able to see your onViewStateRestored() logs.
You should implement the logic of which you are looking in
onActivityCreated
where you get saved instance state.