1

There are three activities: Login, Main and Profile

Obviously from Login you can go to Main. There is a Button that calls AppCompatDialogFragment in Main.

    BalanceCalculationDialog dialog = BalanceCalculationDialog.newInstance(model);
    dialog.setListener(this);
    dialog.show(getSupportFragmentManager(), "TAG");
  1. If I user enters Main for the first time dialog shows.
  2. If user goes to Profile and then backs dialog shows.
  3. If user goes out from Main (finish() with Intent#FLAG_ACTIVITY_NEW_TASK and Intent#FLAG_ACTIVITY_CLEAR_TASK flags) and tries to see dialog he sees an error.

        java.lang.IllegalStateException: Can not perform this action after 
         onSaveInstanceState....CheckStateLoss()...
    

As far as I know it caused because "Transaction cannot be commited after onSaveInstanceState()".

I tried to override this method leaving empty body, not calling super and didn't work.

Then I found another way to solve problem, which worked:

@Override
public void show(FragmentManager manager, String tag) {
    try {
       FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    } catch (IllegalStateException e) {
        Log.e("ILLEGAL", "Exception", e);
    }
 }

Nevertheless I don't understand why it works this way -> Number of catching IllegalStateException equals the number of recreating Main. For example I log out 20 times - then I will have 20 catching of mentioned exception. So I don't find this solution as the right one.

In addition, I have other activities that can call another dialogs. These activities also can be finished with finish() and when user opens one of them again he doesn't have the issue.

I would be very glad to have proper explanation of such behaviour and right way of solving it. Thank you very much.

EDIT

Reason of this issue was usage of RxJava EventBus. When I switched to Otto Eventbus problem disappeared. RxJava allows you to send and get messages without subscribe and unsubscribe that can cause unexpected behaviour.

2
  • When you show the dialog when you leave 'Main' are you showing it in onFinish? in which case you can't do that which is what the error says, because the activity is being closed so the dialog has no context. Not sure how you've set it up but you could show the error on the Login page.
    – RobVoisey
    Commented Jul 18, 2017 at 14:57
  • @RobVoisey Dialog is shown only on button click in Main
    – Igor SKRYL
    Commented Jul 18, 2017 at 15:07

1 Answer 1

4

The exception was thrown because you attempted to commit a FragmentTransaction after the activity’s state had been saved, resulting in a phenomenon known as Activity state loss. Before we get into the details of what this actually means, however, let’s first take a look at what happens under-the-hood when onSaveInstanceState() is called. Android applications have very little control over their destiny within the Android runtime environment. The Android system has the power to terminate processes at any time to free up memory, and background activities may be killed with little to no warning as a result. To ensure that this sometimes erratic behavior remains hidden from the user, the framework gives each Activity a chance to save its state by calling its onSaveInstanceState() method before making the Activity vulnerable to destruction. When the saved state is later restored, the user will be given the perception that they are seamlessly switching between foreground and background activities, regardless of whether or not the Activity had been killed by the system.

When the framework calls onSaveInstanceState(), it passes the method a Bundle object for the Activity to use to save its state, and the Activity records in it the state of its dialogs, fragments, and views. When the method returns, the system parcels the Bundle object across a Binder interface to the System Server process, where it is safely stored away. When the system later decides to recreate the Activity, it sends this same Bundle object back to the application, for it to use to restore the Activity’s old state.

So why then is the exception thrown? Well, the problem stems from the fact that these Bundle objects represent a snapshot of an Activity at the moment onSaveInstanceState() was called, and nothing more. That means when you call FragmentTransaction#commit() after onSaveInstanceState() is called, the transaction won’t be remembered because it was never recorded as part of the Activity’s state in the first place. From the user’s point of view, the transaction will appear to be lost, resulting in accidental UI state loss. In order to protect the user experience, Android avoids state loss at all costs, and simply throws an IllegalStateException whenever it occurs.

Solution for this exception is

  • Be careful when committing transactions inside Activity lifecycle methods. A large majority of applications will only ever commit transactions the very first time onCreate() is called and/or in response to user input, and will never face any problems as a result. However, as your transactions begin to venture out into the other Activity lifecycle methods, such as onActivityResult(), onStart(), and onResume(), things can get a little tricky. For example, you should not commit transactions inside the FragmentActivity#onResume() method, as there are some cases in which the method can be called before the activity’s state has been restored (see the documentation for more information). If your application requires committing a transaction in an Activity lifecycle method other than onCreate(), do it in either FragmentActivity#onResumeFragments() or Activity#onPostResume(). These two methods are guaranteed to be called after the Activity has been restored to its original state, and therefore avoid the possibility of state loss all together. (As an example of how this can be done, check out my answer to this StackOverflow question for some ideas on how to commit FragmentTransactions in response to calls made to the Activity#onActivityResult() method).
  • Avoid performing transactions inside asynchronous callback methods. This includes commonly used methods such as AsyncTask#onPostExecute() and LoaderManager.LoaderCallbacks#onLoadFinished(). The problem with performing transactions in these methods is that they have no knowledge of the current state of the Activity lifecycle when they are called. For example, consider the following sequence of events: An activity executes an AsyncTask.
    1. The user presses the “Home” key, causing the activity’s onSaveInstanceState() and onStop() methods to be called.
    2. The AsyncTask completes and onPostExecute() is called, unaware that the
    3. Activity has since been stopped. A FragmentTransaction is committed inside the onPostExecute() method, causing an exception to be thrown. In general, the best way to avoid the exception in these cases is to simply avoid committing transactions in asynchronous callback methods all together.
  • Use commitAllowingStateLoss() only as a last resort. The only difference between calling commit() and commitAllowingStateLoss() is that the latter will not throw an exception if state loss occurs. Usually you don’t want to use this method because it implies that there is a possibility that state loss could happen. The better solution, of course, is to write your application so that commit() is guaranteed to be called before the activity’s state has been saved, as this will result in a better user experience. Unless the possibility of state loss can’t be avoided, commitAllowingStateLoss() should not be used.

But I have to agree that this is an Android framework design defect. Google devs try to fix it over many version. But seems like there is no good approach to work-around this. Just understand the life cycle and remember to check the state of activity carefully before committing transaction

2
  • I have already read these info copied from the article. Unfortunately it doesn't help neither to understand my issue when some activity can create dialog being recreated and other don't, nor to find right solution. My dialog can be called only after onResume, there are no asynch calls and even commitAllowingStateLoss() doesn't work perfectly. Sorry, you didn't tell me anything new :(
    – Igor SKRYL
    Commented Jul 18, 2017 at 15:24
  • exactly, it makes no sense. I have a dialog I call on onClick and yet I still get this exception.
    – Smile
    Commented Jul 26, 2018 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.