android.support.v4.app.getFragmentManager() returns null?

前端 未结 4 1368
不知归路
不知归路 2020-12-29 20:41

This is my Stacktrace:

FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.test.fragments.LoadingFragment$1.run(LoadingFragment.java:66)
at a         


        
相关标签:
4条回答
  • 2020-12-29 20:44

    Replace this getFragmentManager() with this getSupportFragmentManager() and also make sure that your activity extends FragmentActivity

    0 讨论(0)
  • 2020-12-29 20:46

    From android.support.v4.app.Fragment source:

    // The fragment manager we are associated with.  Set as soon as the
    // fragment is used in a transaction; cleared after it has been removed
    // from all transactions.
    FragmentManagerImpl mFragmentManager;
    

    Apparently getFragmentManager() returns support version of fragment manager but only during a transaction (or parent fragment's child fragment manager).

    I'm going to use this:

    public FragmentManager getHostFragmentManager() {
        FragmentManager fm = getFragmentManager();
        if (fm == null && isAdded()) {
            fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
        }
        return fm;
    }
    
    0 讨论(0)
  • 2020-12-29 20:51

    CASE: When you need to call Fragment(Child fragment) from another Fragment(Parent Fragment)

    always use getChildFragmentManager() instead of getFragmentManager() inside your Parent Fragment.

    0 讨论(0)
  • 2020-12-29 20:55

    After cleaning and rebuilding my project aswell as restarting my testing device, this worked again somehow.

    0 讨论(0)
提交回复
热议问题