GetSupportFragmentManager (). findFragmentById (R.id.map) started to return null

I have a map fragment inside another fragment. This worked before, but I think it went wrong after I updated the Google Play services library. What's wrong? fragment_map.xml:

<fragment android:name="com.google.android.gms.maps.SupportMapFragment" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" /> 

MapFragment:

 GoogleMap map; private static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.fragment_map, container, false); map = ((SupportMapFragment) getActivity() .getSupportFragmentManager() .findFragmentById(R.id.map)) .getMap(); // NullPointerException at this line map.getUiSettings().setAllGesturesEnabled(true); map.getUiSettings().setMyLocationButtonEnabled(false); map.getUiSettings().setZoomControlsEnabled(true); } catch (InflateException e) { /* map is already there, just return view as it is */ } return view; } 
+5
source share
3 answers

I had to change

 getActivity().getSupportFragmentManager() 

to

 getChildFragmentManager() 

to make it work. I donโ€™t know why it worked perfectly a few days ago.

+20
source

This is the answer:

Note. You cannot inflate a layout into a fragment if this layout contains a fragment. Nested fragments are supported only when dynamically adding a fragment.

+1
source

In onCreateView you should not do this. Use the proposed method in the official documentation for intersectoral communication. Here, I think your problem is time related. Not all fragments are created or managed synchronously. Also, I'm not very sure that you can call getActivity () from onCreateView () - because the fragments will receive the onActivityCreated () callback only after onCreateView ().

0
source

Source: https://habr.com/ru/post/1212372/


All Articles