Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 963
Arturs Vancans Avatar asked Feb 23 '13 15:02

Arturs Vancans


2 Answers

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.

like image 160
Flynn81 Avatar answered Oct 31 '22 19:10

Flynn81


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();
}
like image 29
S.D. Avatar answered Oct 31 '22 20:10

S.D.