1

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
}
Abhijith Madhav
  • 2,748
  • 5
  • 33
  • 44

2 Answers2

0

have you tried this

filter = (Filter) view.findViewById(R.id.fragment_filter);
Ali
  • 1,857
  • 24
  • 25
0

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.

lahodal
  • 11
  • 4