Search code examples
androidfragmentlifecycle

I have a trouble in Fragment life cycle and need a resolution to come out of it


I have done ample research on this, and there is not one clear solution on the problem.

In the life-cycle, particularly in the Fragment life-cycle, following Exception comes any moment after onPause().

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

My logic says, that to continue with the current fragment, after it reaches this state, I have to restart the activity and again point back to the intended fragment using Intent.

I want to be clear on what is happening and what should be real solution to deal with it.

I need to know the pros and cons of this mechanism; its importance in Fragment or Activity life-cycle.

Also, if I am changing the Windows Feature in onCreate to not to go to sleep, unless if the user has manually pressed the home button, will still the activity will go to this state?


Solution

  • A better explanation is presented in a new Android developer reference and guide documents for using JetPack Life Cycle Listener.

    https://developer.android.com/topic/libraries/architecture/lifecycle#kotlin

    The library makes the components Activity Life Cycle aware. That means you do not require an abstract baseActivity class which overrides every life cycle callback, and record that state in a boolean variable. LifeCycle listener will do it for you.

    All you have to do is stop introducing a new fragment or stop any Loader that updates the UI when its response returns. The right time to do this is before onStop or onSavedInstance state is called, and your components will be made aware of it.

    It clearly states that after the onSavedInstancState or onStop is called the UI becomes immutable till the onStart of the Activity is called again. Sometimes you have to call restart the same activity using NEW TASK and CLEAR TASK flags using intent, when this state occurs and there is no chance that otherwise onStart is going to be called.

    Happy Coding :-)