简体   繁体   中英

Mapbox not working in fragment

I am trying to display a mapbox in a fragment but I am getting the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onResume()' on a null object reference

Here is the Map fragment class:

public class Map extends android.support.v4.app.Fragment {
    private MapView mapView;

public Map() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.fragment_map, container, false);

    MapView mapView = (MapView) layout.findViewById(R.id.mapview);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {

            // Set map style
            mapboxMap.setStyleUrl(Style.MAPBOX_STREETS);

            // Set the camera's starting position
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(41.885, -87.679)) // set the camera's center position
                    .zoom(12)  // set the camera's zoom level
                    .tilt(20)  // set the camera's tilt
                    .build();

            // Move the camera to that position
            mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }


    });
    return layout;
}

@Override
public void onResume() {
    super.onResume();
    mapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mapView.onPause();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}
}

Am I missing something here? I was following this link: https://www.mapbox.com/help/first-steps-android-sdk/

You have two mapview instances. one is local variable inside oncreate method and another one is global variable.

And the global variable isn't initalized, So change this line

MapView mapView = (MapView) layout.findViewById(R.id.mapview);

into this

mapView = (MapView) layout.findViewById(R.id.mapview);

I think you understand the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM