Lumbi
Lumbi

Reputation: 688

Fragment isAdded() returns false on an already added Fragment

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?

Upvotes: 20

Views: 24951

Answers (2)

km86
km86

Reputation: 485

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

Upvotes: 0

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

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.

Upvotes: 42

Related Questions