Android Fragment destroyed but gets onActivityResult

thanks to this answer Android fragment lifecycle problem (NullPointerException on onActivityResult) I was able to re-create the script when I get NPE in my fragment after calling startActivityForResult. Therefore I have

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, PHOTO_SELECT_REQUEST_CODE); break; 

is called from my fragment, then my activity gets onPause, onStop and onDestroy, so the fragment called startActivityForResult also gets onDestroy. After I select an image, I get a new onCreate in my activity, and then get a public void onActivityResult in my original fragment, which is now destroyed.

My question is that this is a potential (albeit rare) situation, how would I restore the entire stack of fragments and objects transferred to them, and what does it do to prevent the leak of the original fragment?

+6
source share
1 answer

When your code executes the following line:

 startActivityForResult(photoPickerIntent, PHOTO_SELECT_REQUEST_CODE); 

Your activity will receive onPause() , onStop() , but not onDestroy() every time. If the android system is not working at this time, your activity can get onDestroy()

To maintain fragment status and activity and prevent leakage:

Save state in onSaveInstanceState(Bundle)

In situations where the system needs more memory, it can kill paused processes (after onPause() ) to restore resources. Because of this, you must be sure that all your state will be saved by the time you return from this function. Typically, onSaveInstanceState(Bundle) used to store the state of each instance in activity, and this method is used to store global persistent data (in content providers, files, etc.).

Restore your state in onRestoreInstanceState(Bundle)

onRestoreInstanceState(Bundle) method is called after onStart() when the activity is reinitialized from the previously saved state specified here in savedInstanceState . Most implementations simply use onCreate(Bundle) to restore their state, but sometimes it’s convenient to do it here after initialization is completed or to allow subclasses to decide whether to use your default implementation. By default, the implementation of this method restores any view state that was previously frozen using onSaveInstanceState(Bundle) .

It can help you fulfill your requirement.

0
source

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


All Articles