Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Parent fragment of a nested fragment

A getParentFragment() from my nested fragment is returning a null. I realise that getting a null means that the fragment is attached to the activity and not to the nested container fragment. But I am explicitly nesting the child fragment inside the parent fragment using the child FragmentManager and thus think that I should not be getting a null. Could you tell me what I am missing?

Parent fragment

public class UsageBreakUp extends Fragment implements Filter.OnFragmentInteractionListener {    ....    @Override     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {         super.onViewCreated(view, savedInstanceState);         getChildFragmentManager().beginTransaction().add(R.id.filter, new Filter()).commit();     }  ...  } 

Child fragment

public class Filter extends Fragment {  ...       public Filter() {         if (getParentFragment() == null)             Log.d(LOG_TAG, "parent fragment is null");     }  ...  } 
like image 869
Abhijith Madhav Avatar asked Nov 18 '14 10:11

Abhijith Madhav


People also ask

How to share data between two fragments in Android?

When working with child fragments, your parent fragment and its child fragments might need to share data with each other. To share data between these fragments, use the parent fragment as the ViewModel scope.

What is parent fragment manager?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.

How to pass listener to fragment?

You need to call an extra method every time you want to instantiate the Fragment . You can't guarantee that mListener is set at any time. You may need to pepper your Fragment code with null checks. You need to be careful to make sure the listener remains set after lifecycle events such as screen rotation.


1 Answers

I was calling getParentFragment() in the constructor of the child fragment and thus before the child fragment was fully created. Shifting getParentFragment() to onCreateView() solved the problem. Shifting wasn't an issue as I was calling getParentFragment() to check if the parent fragment had implemented a child fragment interaction listener.

like image 54
Abhijith Madhav Avatar answered Oct 07 '22 10:10

Abhijith Madhav