androidandroid-fragments

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();

Solution

  • 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.