Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getParentFragment returning null

I have a Fragment that has a FrameLayout. This first fragment (A) loads inside its Framelayout another fragment (B). When I call getParentFragment from inner fragment (B), I get null. How should this method be used properly?

like image 803
Gonzalo Avatar asked Feb 11 '13 00:02

Gonzalo


4 Answers

getParentFragment() was introduced in API level 17 (Android 4.2). Android 4.2 introduced the idea of nested fragments (fragments containing other fragments). Calling this results in null if the fragment has a parent which is an Activity.

Have a look at this.

If you are using support library then you can use getParent(), may be you need to use getChildFragmentManager() while doing fragment transaction. See this

like image 185
Eurig Jones Avatar answered Nov 07 '22 16:11

Eurig Jones


In my case, although my fragmentA was nested in fragmentB,but I still get null after call getParentFragment in FragmentA. Finally I found that I should use getChildFragmentManager rather than getFragmentManager in FragmentB.

check this What is difference between getSupportFragmentManager() and getChildFragmentManager()?

like image 30
muyiou Avatar answered Nov 07 '22 16:11

muyiou


The one thing that helped is, when creating adapter use getChildFragmentManager().

If you are not using adapter, just use getChildFragmentManager() when doing transactions.

setTargetFragment() is not recommended, since it gives errors on moveState() of fragment(because fragments should be tied to FragmentManager)

like image 5
Aibol Kussain Avatar answered Nov 07 '22 15:11

Aibol Kussain


I faced the same issue , and fixed the issues by hosting second fragment in your parent fragment with getChildFragmentManager() then you wont be getting the null value ...

Parent fragment

  SignUpFragment signUpFragment = new SignUpFragment();
    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.contentPanel, signUpFragment)
            .addToBackStack(null).commit();

Child fragment : what i have used is a dialog

 HospitalCardDialog hospitalCardDialog = new HospitalCardDialog();
    hospitalCardDialog.show(getChildFragmentManager(), "");
like image 5
Ameen Maheen Avatar answered Nov 07 '22 15:11

Ameen Maheen