20

I have this neat function:

private void addMapFragment(){
    if(!mapFragment.isAdded()){
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.mapContainer, mapFragment);
        ft.commit();
    }
}

I'm calling addMapFragment() in my activity's onCreate(). I then have a callback from a webrequest that calls addMapMapFragment(). The isAdded() method doesn't look useful at all since I'm getting a crash saying "Fragment already added: MapFragment[...]"

Any clue?

Lavekush Agrawal
  • 6,040
  • 7
  • 52
  • 85
Lumbi
  • 688
  • 2
  • 8
  • 17

2 Answers2

42

FragmentTransactions are committed asynchronously. Therefore, you need to call

getFragmentManager().executePendingTransactions();

before you call

Fragment.isAdded();

That way, you can make sure that everything is up to date.

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
  • 1
    Thanks Philipp for the title edit for clarity. I'm not getting this crash anymore although I have a new issue with a NPE in FragmentManagerImpl.execPendingActions. I guess there's something I'm not doing quite right. I also made sure to run executePendingTransactions() on the UI Thread. – Lumbi Mar 19 '14 at 07:35
0

Instead, check getSupportFragmentManager.findFragmentById() and see if you are getting the expected fragment back. If now you can add and commit.

km86
  • 475
  • 3
  • 6
  • The bummer with that solution is that it's relatively expensive. – Laurent Oct 07 '15 at 05:26
  • @Laurent Not actually, `getFragmentManager().executePendingTransactions();` will force everything to be executed in Main thread synchronously. Which is much worse than `getSupportFragmentManager.findFragmentById()`. – Farid Jun 10 '21 at 07:36