0

In my project im trying to implementthis solution for managing a map in a dynamic added fragment.

public class MapFragment extends Fragment {
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap map;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =inflater.inflate(R.layout.fragment_map, container, false);

        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

        Marker kiel = map.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_arrow)));

        // Move the camera instantly to hamburg with a zoom of 15.
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(KIEL, 15));
        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
        return v;
    }
}

My view:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/ColorBackground"
    tools:context="com.example.sven.questy.GameFragments.MapFragment">

    <fragment

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

</RelativeLayout>

WHen i run the app i get a nullpointer exception on:

 map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

The id of the map = map ( android:id="@+id/map").

Why the nullpointer?

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

2 Answers2

2

Since you are using nested fragments, you should use getChildFragmentManager()

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

And I recommend you to use getMapAsync method, because getMap is deprecated

mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        setupMap(googleMap);
    }
});
Stas Parshin
  • 7,973
  • 3
  • 24
  • 43
-1

You need to use findViewById on the view you get, not using the fragment manager. The map is attached to the view

    View v =inflater.inflate(R.layout.fragment_map, container, false);

    map = v.findViewById(R.id.map))
            .getMap();
Diego Freniche
  • 5,225
  • 3
  • 32
  • 45