1

I have within an Activity, called CounterActivity, a counter that counts let's say from 100 down to 0 with a second interval. A DialogFrament is shown when the counter gets to 0 as follows:

MessageFragment dialog = new MessageFragment();
dialog.show(getSupportFragmentManager(), "MessageFragment");

The main layout of that activity has the following attribute set android:keepScreenOn="true",that way the screen will not timeout as long as the activity is visible. If I then open another application then onStop is called on CounterActivity. If the counter, which is still running in the background, gets to 0 instead of showing the DialogFragment the following exception is thrown:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
  • you should first check if your activity is still available before you do anything after your other thread finishes. you may put a null check with context. – Junaid Hafeez Mar 16 '17 at 20:56

1 Answers1

0

You cannot do fragment transactions when your activity is not on screen for UI reasons (your activity may be killed then restored, thus, any UI change won't be made again).

Therefore you must avoid any UI change when your activity is not active. You have multiple solutions to handle the problem : 1-You can simply register a boolean "showDialogOnResume", then override your "public void onResume()" :

@Override
public void onResume() {
    super.onResume();
    if(showDialogOnResume) {
        /*build your dialog here*/
        dialog.show(getSupportFragmentManager(), "MessageFragment");
    }
}

If you are doing this in activity (not in fragment) i hevily recommand to do override "onPostResume()" instead. Look this post and especially jed answer and pjv comment.

It may even happen that you are not calling :

super.onActivityResult();

On your "onActivityResult()"; as Sufian said in his comment to jed answer.

Basically : avoid any UI change during activity lifecycle. Allow it only when your activity is active. If you cannot do that (other threads like AsyncTasks), get the answer, save it somehow, and perform your change on your activity result. Because if the user never resume your activity, you don't need to do your changes.

Community
  • 1
  • 1
Feuby
  • 708
  • 4
  • 7