Matt Greencroft has his say

Matt's Blog

Errata for Android course Module 2 Chapter 4

06-Sep-2018 in Errata

In Chapter 4 of the Android course (module 2) the fragment manager is able to "look through" fragments to find nested fragments. Unfortunately this behaviour no longer works in the current version of Android, so a slightly different approach is needed...

In this chapter, when we set the current question we use the following line of code to reference the fragment containing the question:

QuestionFragment fragment1 = (QuestionFragment)getFragmentManager().findFragmentById(;

When we introduce the new layout for larger screens, our fragmentQuestion1 is being placed inside another fragment which we called fragmentQuestionSet. So in this instance fragmentQuestion1 is a nested fragment.

When the course was recorded,


worked fine - that is the fragment manager was able to "look though" fragments to find nested fragments.

Unfortunately this behaviour has changed, and Android can no longer do this look-through. As a result, the code will give a null pointer exception, saying that fragment1 was not set.

To get around this problem we need to change our code to reference the containing fragment first. This fragment then provides us with a method called getChildFragmentManager() which can be used to find the nested fragment. The following lines of code are an example:

QuestionFragment fragment1 = (QuestionFragment)getFragmentManager().findFragmentById(;
if (fragment1 == null) {
QuestionSetFragment questionSetFragment = (QuestionSetFragment)getFragmentManager().findFragmentById(;
fragment1 = (QuestionFragment)questionSetFragment.getChildFragmentManager().findFragmentById(;

The code in the closing workspaces for the course has been updated to reflect this change.

Listen via:

About Matt

I'm a Java developer and trainer for Virtual Pair Programmers, where I present video based training courses on Java, Spring and associated frameworks. I'm currently working on a few different web projects.

Be notified of new posts