Android : Parent fragment of a nested fragment

Abhijith Madhav picture Abhijith Madhav · Nov 18, 2014 · Viewed 33.8k times · Source

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");
    }

...

}

Answer

Abhijith Madhav picture Abhijith Madhav · Nov 18, 2014

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.