Arturs Vancans
Arturs Vancans

Reputation: 4640

How to check if the fragment exists?

I am trying to talk to the fragment from activity, but I am not sure if the fragment is visible or no. If the fragment does not exist, I cannot even do null check as it throws exception due to the casting.

How do I check if the fragment exists?

PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
playerFragment.onNotificationListener.updateUI();

Upvotes: 15

Views: 27680

Answers (2)

s.d
s.d

Reputation: 29436

Casting null to a reference won't throw an exception, to a primitive, it will.

Use findFragmentById() or findFragmentByTag() to get a reference and check if its null, if not, check the reference's isAdded() or isVisible().

PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if( p != null && p.isAdded()){
   p.onNotificationListener.updateUI();
}

Upvotes: 12

Flynn81
Flynn81

Reputation: 4178

Don't cast it at first.

Fragment f = mManager.findFragmentById(R.id.bottom_container);
if(f != null && f instanceof PlayerFragment) {
    PlayerFragment playerFragment = (PlayerFragment) f;
    playerFragment.onNotificationListener.updateUI();
}

If that doesn't work post the stacktrace with the exception you are receiving.

Upvotes: 30

Related Questions