I have 2 fragments in landscape mode, versus 1 fragment in portrait. I'm loading said fragments via the xml method. Anyway, I'm checking for the existence of the second fragment in the first activity, and either launching the second fragment's activity or calling a method directly on the second fragment. Everything works fine, however, when the user initially rotates (creating two fragments) then rotates back, my check for the second fragment is now not null and breaking the logic as it's been added to the backstack.
How to resolve this? Do I need to remove the fragment from the history stack in onPause() perhaps? Or maybe prevent the second fragment from ever being added to the backstack somehow.
FirstActivity:
public void onClick(View view) {
SecondFragment secondFragment = (SecondFragment) getSupportFragmentManager().findFragmentById(R.id.second_fragment);
if (secondFragment != null) { // * this will no longer be not null after rotating
// two pane layout : update second fragment
secondFragment.updateSecondFragmentView();
} else {
// one pane layout : start second activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
}
}
SecondFragment: Do you recommend this?
@Override
public void onPause() {
super.onPause();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}