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();
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With