I'm running i开发者_StackOverflownto an issue where I have an Activity with multiple fragments. For any individual fragment, you can perform a search operation, which works just fine...if you search from any of the fragments, it will display a new Activity to handle the searching, then return the result to the Activity to handle displaying a new fragment. The problem is, after a search operation, I want to be able to clear (almost) all the fragments away using popBackStackImmediate(...)
and since saveInstanceState(...)
was called, I get an exception that says:
"java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState"
Any idea how to pop from the back stack after onSaveInstanceState
has been called?
Apparently my issue spawned from the call being made in onActivityResult(...)
I was able to fix the issue by putting the UI modification code inside a Runnable, then posting the Runnable to the main thread:
Runnable r = new Runnable() {
@Override
public void run() {
// UI code here
}
};
Handler h = new Handler();
h.post(r);
call super.onActivityResult
first before your logic and the issue will get fixed as FragmentActivity's onActivityResult
calls mFragments.noteStateNotSaved();
This answer is may help to someone. When your activity is not visible, you unable to call popBackStackImmediate(...) it will throw illegal Exception: can not perform this action after onsaveinstancestate.
Instead of that you can check, Is the activity is visible or not? before call the popBackStackImmediate().
If your activity is not visible, don't call popBackStackImmediate. Through the boolean flag you can achieve, when activity opens again.
Ex:
public class MainActivity extends Activity {
// Below flag used to check activity visible or not?
private boolean isActivityVisible;
@Override
public void onResume() {
super.onResume();
isActivityVisible = true;
}
public void onPause() {
super.onPause();
isActivityVisible = false;
}
}
What about popping the stack immediately before starting your associated activity? onSaveInstanceState wouldn't be called until startActivity was called (and the new activity came in front of the current one0... immediately before that, pop the fragment stack back to your desired state and then call startActivity.
Since the fragment stack is a layer over the normal task/back stack, I think that modifying it "from the middle" would cause issues and that's why you're seeing the issue.
This is what worked for me is to check if fragment manger doesn't hava a saved state
if (fragmentManager != null && !fragmentManager.isStateSaved()) {
fragmentManager.popBackStack();
}
Or just put it in a try-catch:
try {
getSupportFragmentManager.popBackStack()
} catch (IllegalStateException e) {
// ignore
}
This is basically the same as commitAllowingStateloss()
except we don't have a popBackStackAllowingStateloss()
.
In most cases I get an error even though I don't need to save state.
精彩评论