Android : Referencing child fragment from parent fragment

901 views Asked by At

I have nested fragment scenario. Attempts to reference the child fragment from the parent fragment gives a null. What am I missing here?

This is the layout file of the parent fragment.

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Statically nested fragment -->
    <fragment
        android:name="reports.fragments.fragments.usageBreakUp.fragments.Filter"
        android:id="@+id/fragment_filter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Here is how I am trying to access the child fragment from the parent fragment

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Log.i(LOG_TAG, "ON VIEW CREATED");

    filter = (Filter) getChildFragmentManager().findFragmentById(R.id.fragment_filter);
    filter.populateStorageFilter(); // NPE here
}
2

There are 2 answers

0
lahodal On

You probably get NPE inside populateStorageFilter because your child fragment's onViewCreated hasn't been called yet, i.e. child's view hasn't been initialized. So if you use any view references inside populateStorageFilter, they are null. You have to wait for child fragment's view to create and then call populateStorageFilter.

0
Ali On

have you tried this

filter = (Filter) view.findViewById(R.id.fragment_filter);