I have a viewpager holding many fragments. When the activity is sent to background and when resources are needed, the OS will kill the app or at least some fragments. When I return to the activity it crashes because the activity tries to attach new instances of all fragments it held before the clean-up and now some fields are null. This of course could be fixed by properly implementing state saving and restoring using Bundles, but I don't want to do that. Instead I want to prevent restoring the fragments. Is there a way to tell the OS that once it has sent the GC in and destroyed fragments, it shouldn't bother recreating them at all? Once the cleaning-up happens, I want the activity to be simply recreated on return, as if a user launched it by taping the icon. Any chance of doing that?
The proposed solution here https://stackoverflow.com/a/15683289/552735 does not work. It causes exceptions java.lang.IllegalStateException: Fragement no longer exists for key f2: index 3
So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.
Task affinity lets you define which task an activity belongs to. By default, an activity has the same task affinity as its root activity. With task affinity, we can now separate activities into different tasks.
State can be restored in either the onCreate() or the onRestoreInstanceState() methods of the activity by extracting values from the Bundle object and updating the activity based on the stored values.
I had a problem just like this. Here's how I fixed it:
@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.clear();
}
Note that this method will ensure that absolutely no UI state information will be stored when the Activity is killed by the system - this has the effect of also not restoring any Views when onRestoreInstanceState()
gets called with the same Bundle after onStart()
.
You can't disable the save/restore instance state actions. In case you don't want to actually implement this logic, you have to reload the form especially if your form heavily loaded with fragments.
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
startActivity(new Intent(this,YOUR_ACTIVITY.class));
finish();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With