This is an action lifecycle issue. When you call startActivityForResult() , the start action is paused and can, if Android lacks resources, be completely destroyed.
When you return from the action you started, the call to onActivityResult() occurs at an early stage of the activity life cycle - for example, calling the getActivity () function inside onActivityResult() in a fragment returns null if the action was actually destroyed, but returns non-zero if it was not destroyed.
Therefore, you cannot reliably do anything complicated with the onActivityResult() method. I have two templates that I use here. First, just use onActivityResult() to store the response in instance variables, and then do the action in the onResume() method; the second is to conditionally execute the code:
@Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (getActivity() != null) {
Which solution you use depends on the scenario you are dealing with. I use the first solution when the transient data is returned through the data intent (since this is the only way to get it), and the second when the onActivityResult() call is just a notification that I should update the view from the saved data elsewhere.
source share