0

I have a very strange error I can't figure out.

I have 1 main Fragment and many secondary fragments. A->(B,C,D,E,F) where Fragment A should always stack on backstack but fragments B,C,D,E should change in and out.

I use these lines of code to do this:

    getFragmentManager().executePendingTransactions();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    MyFragment mListFragment = new MyFragment();
    transaction.replace(R.id.listFragmentPlaceHold, mListFragment, FRAGMENT_TAG);
    if(getFragmentManager().getBackStackEntryCount() == 0)
            transaction.addToBackStack(null);
    transaction.commit();

The problem is this, if I go from Fragment A to Fragment B and the hit back button everything works correctly. I can do this as many times as I like.

Then, when I go A->B then switch out B a few times, A->(B,C,D) and hit back, I am still good, I get back to A. But, when I have done the above, and then I try to do it again. I again go from A -> B (without restarting activity) and then switch out B to C, D and then hit back, Fragment A is no longer there and I get a Null Pointer Exception.

Could someone please help me out, this is driving me nuts.

I always use getFragmentManager().executePendingTransactions(); before I try to reference Fragment A.

Thank you!

AlexIIP
  • 2,461
  • 5
  • 29
  • 44
  • The problem might be similar to [this](http://stackoverflow.com/a/14283203/1079311) one but their solution did not help. – AlexIIP Jun 10 '13 at 21:09

1 Answers1

0

So after reading this and this post, I realized that replace() calls remove() which should call the onDestroy() method for the Fragment, in my case Fragment A associated with the view, thus if i called replace(), there is no guarantee that Fragment A would still be there and would not be re-created. Therefore, I used detach() instead to solve the problem.

My understanding may be wrong...but this did fix the problem:

getFragmentManager().executePendingTransactions();
MyFragment1 mListFragment1 = 
           (MyFragment1) getFragmentManager().findFragmentByTag(MY_FRAG1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
MyFragment mListFragment = new MyFragment();
transaction.replace(R.id.listFragmentPlaceHold, mListFragment, FRAGMENT_TAG);
if(getFragmentManager().getBackStackEntryCount() == 0){
      transaction.detach(mListFragment1);
      transaction.add(R.id.listFragmentPlaceHold, mListFragment, FRAGMENT_TAG);
      transaction.addToBackStack(null);
}else{
      transaction.replace(R.id.listFragmentPlaceHold, mListFragment, FRAGMENT_TAG);
}
transaction.commit();
Community
  • 1
  • 1
AlexIIP
  • 2,461
  • 5
  • 29
  • 44