Mapbox在碎片中无法工作

3
我正在尝试在一个fragment中显示mapbox地图,但是我遇到了以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mapbox.mapboxsdk.maps.MapView.onResume()' on a null object reference 这是Map fragment类的代码:
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/

。这个链接是关于Android SDK开发的文档,你是否需要帮助?


请参考这个链接:https://dev59.com/6o_ea4cB1Zd3GeqPKicQ#32601861 - Emil
我正在使用Mapbox,它仍然是同样的方式吗?@Boss - Tirth Allspark Rami
嗯,我找到了你的问题。 - Emil
1个回答

4
你有两个地图视图实例,一个是在oncreate方法内的局部变量,另一个是全局变量。而全局变量没有初始化,所以更改这行代码。
MapView mapView = (MapView) layout.findViewById(R.id.mapview);

转换为这样

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

我想你理解这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接