getActivity() in fragment is null after orientation change

Viewed 4260

I have a problem with startActivityForResult, fragments and orientation changes.

I call startActivityForResult() from one fragment, then I open second activity with fragment attached. In this second activity when I change orientation and go back to the first activity then onActivityResult (fragment method) is called. But there's a problem, because a I have something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    getActivity(); //here's a problem because 
    //getActivity is null but only after orientation change on second activity 
}
3 Answers

This solved for me:

private Activity activity;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    this.activity = getActivity();
}

and use this activity anywhere in the fragment that you need.

Related