findFragmentById for SupportMapFragment returns null in Android Studio

Judging by the fact that you’re overriding Fragment.onActivityCreated(), I take it that your layout containing the map fragment is the layout for your Fragment. In that case, the SupportMapFragment is a child fragment of your hosting Fragment. When you attempt to retrieve it, you’re using the Activity FragmentManager. You should instead use your Fragment‘s FragmentManager:

For example, this:

SupportMapFragment m = ((SupportMapFragment) getActivity()
        .getSupportFragmentManager().findFragmentById(R.id.safety_map));

becomes:

SupportMapFragment m = ((SupportMapFragment) getChildFragmentManager()
        .findFragmentById(R.id.safety_map));

Leave a Comment