Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

popBackStack() after saveInstanceState()

I'm running into 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?

like image 431
Chris Avatar asked Sep 19 '11 17:09

Chris


People also ask

How can I maintain fragment state when added to the back stack?

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

How to Save state of a fragment?

Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.

What is BackStack in fragment?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.

How to add fragment to fragment Manager?

You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


2 Answers

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); 
like image 172
Chris Avatar answered Sep 23 '22 05:09

Chris


call super.onActivityResult first before your logic and the issue will get fixed as FragmentActivity's onActivityResult calls mFragments.noteStateNotSaved();

like image 25
Shilpi Avatar answered Sep 21 '22 05:09

Shilpi