Android prevents activity recovery

I have a viewpager containing many fragments. When activity goes to the background and when resources are needed, the OS will kill the application, or at least some fragments. When I return to the activity, it crashes because the activity is trying to attach new instances of all the fragments that it spent before clearing, and now some fields have a zero value. This, of course, could be corrected by correctly performing state saving and recovery using the Bundles, but I do not want to do this. Instead, I want to prevent fragment recovery. Is there any way to tell the OS that after it sends the GC and destroys the fragments, it should not bother to recreate them at all? As soon as the cleanup happens, I want the activity to be simply recreated upon return, as if the user started it by clicking on the icon. Is there any chance of this?

The proposed solution here is https://stackoverflow.com/a/318618/ This throws java.lang.IllegalStateException: Fragement no longer exists for key f2: index 3

+6
source share
2 answers

I had a problem that way. Here is how I fixed it:

@Override protected void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.clear(); } 

Please note that this method ensures that UI state information will not be saved when activity is killed by the system - it will also not restore any views when onRestoreInstanceState() is called with the same package after onStart() .

+8
source

You cannot disable the state actions of the save / restore instance. If you do not want to implement this logic, you need to reload the form, especially if your form is heavily loaded with fragments.

 @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); startActivity(new Intent(this,YOUR_ACTIVITY.class)); finish(); } 
0
source

Source: https://habr.com/ru/post/951173/


All Articles