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
}
You probably get NPE inside
populateStorageFilter
because your child fragment'sonViewCreated
hasn't been called yet, i.e. child's view hasn't been initialized. So if you use any view references insidepopulateStorageFilter
, they arenull
. You have to wait for child fragment's view to create and then callpopulateStorageFilter
.