findFragmentByTag() returns null after perform a FragmentTransaction using replace() method

I've fixed it! I called getSupportFragmentManager().executePendingTransactions() after doing the transaction and it worked! After calling that method I can get the fragment using both findFragmentById() and findFragmentByTag() methods.


if you use setRetainInstance(true) than you can't use findFragmentByTag() in onCreate from the Activity. Do it at onResume

see the documentation: setRetainInstance


I'll start by apologising since I'm still very new myself...

I think the problem may be in the declaration of the fragmentTag static String not properly getting access from the class's instances, just change that line to:

private final static String FRAGMENT_TAG = "FRAGMENTB_TAG"; // using uppercase since it's a constant

Also, I would be more explicit when declaring instances, for example:

public void buttonListener(View v){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.right_container, new FragmentB(), FRAGMENT_TAG);
    ft.commit();

    FragmentB fragB = (FragmentB) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
    fragB.testView();
}

I hope you get this sorted, as I seen this question posted earlier and was surprised that it hadn't got any activity yet.

Also, here are a couple of links to the android documentation on replace:

Android Training - Replace

Android Reference - Replace


I had the same problem and realized that there is a really simple way to fix this. When using a tag please do make sure to add the

fragmentTransaction.addToBackStack(null); 

method so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.

You can find this at the end of this section.

Every time I tried to reference back to my created Fragment, it turns out it had already been destroyed so I lost about 30 minutes trying to figure out why my Fragment was not being found through a simple findFragmentByTag(); call.

Hope this helps!