So, I have a fragment - fragment A - which contains an object - object O - used for setting up TextViews and other elements. To instantiate the fragment I use a static method A.getInstance(O). Object O is serializable so I can send it to the new instance of fragment A through a Bundle by using instance.setArguments and so on.
I retrieve O in the onCreate method of A and setup the fields using O in onViewCreated. Everything works fine until here. After I replace A with another fragment - fragment B - and navigate back from B to A, the arguments Bundle doesn't contain object O anymore and I get NullPointerException. The Bundle itself is not null, but it doesn't contain O.
I use this method to replace fragments:
public void replaceCurrentFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = context.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment).addToBackStack(null).commit();
}
Fragment A is also displayed using the method above.
What am I doing wrong?
Fragment#getArgumnets()
? Did you try to save and restore object O from Fragment instance state? – Oleh Toder