java-Mapbox无法在片段中工作

我正在尝试在片段中显示地图框,但出现以下错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void com.mapbox.mapboxsdk.maps.MapView.onResume()”

这是Map片段类:

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();
}
}

我在这里想念什么吗?我正在关注此链接:https://www.mapbox.com/help/first-steps-android-sdk/

解决方法:

您有两个mapview实例.一个是oncreate方法内的局部变量,另一个是全局变量.

且全局变量未初始化,因此请更改此行

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

进入这个

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

我认为您了解这个问题.

上一篇:javascript-如何将地图位置(纬度,经度)对转换为地图框中的屏幕位置(x,y)对


下一篇:javascript – 使用基于本地geojson文件的mapbox进行3D挤压