Search code examples
javaandroidandroid-fragmentsdictionarysupportmapfragment

Android getMapAsync in Fragment


You need to get the map management in the fragment.

My code

public class Fragment1 extends android.support.v4.app.Fragment implements OnMapReadyCallback{

GoogleMap gm;

private void initializeMap() {
    if (gm == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
        mapFrag.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    gm = googleMap;
    setUpMap();
}

public void setUpMap()
{
    Log.d(LOG_TAG,"Map load!");
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    initializeMap();
    return inflater.inflate(R.layout.need_help_view, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

}

error

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference

what is the problem?


Solution

  • You are initializing map without even inflating the view....so your mapFrag is null.

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        initializeMap();
        return inflater.inflate(R.layout.need_help_view, container, false);
    }
    

    Try this:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.need_help_view, container, false);
        if (gm == null) {
            SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
            mapFrag.getMapAsync(this);
        }
        return v;
    }