问题
I have a problem with mapbox when changing the mapStyle from Style.MAPBOX_STREETS to Style.SATELLITE_STREETS (and vice versa) quickly in a row. (This happens with other styles too, those are just examples)
My code:
public void btnChangeMapType(View view) {
this.mapboxMap.getStyle(style -> {
String styleUri = this.mapboxMap.getStyle().getUri();
if (this.animator != null)
this.animator.cancel();
if (styleUri.equalsIgnoreCase(SATELLITE_STREETS)) {
changeMapType(Style.MAPBOX_STREETS, this.mapboxMap.getStyle());
} else {
changeMapType(Style.SATELLITE_STREETS, this.mapboxMap.getStyle());
}
});
}
private void changeMapType(String mapboxMapType, Style mapboxStyle) {
this.mapboxMap.setStyle(mapboxMapType, style -> {
if (this.previousLocation != null) {
this.positionGeoJson = new GeoJsonSource(MAP_LAYER_SOURCE_ID, Feature.fromGeometry(Point.fromLngLat(this.previousLocation.getLongitude(), this.previousLocation.getLatitude())));
} else {
this.positionGeoJson = getNewGeoJsonPosition();
}
if (this.hasFocus && this.animator != null) {
drawDrivenLine();
this.animator.start();
}
});
}
And if i click on a Button that calls btnChangeMapType quickly multiple times i get an error on Line String styleUri = this.mapboxMap.getStyle().getUri(); in btnChangeMapType()
Error Log:
2020-02-20 11:31:50.828 14916-14916/at.myprojects.project E/Mbgl-MapChangeReceiver: Exception in onDidFinishLoadingStyle
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mapbox.mapboxsdk.maps.Style.getUri()' on a null object reference
Is there a way too keep my app from crashing/having this error?
回答1:
In String styleUri = this.mapboxMap.getStyle().getUri();
, the getStyle()
is not needed because you're already in the getStyle()
block that returns a Style
object above that line (the style -> {
). So it'd be String styleUri = style.getUri();
instead. I think this will solve the NullPointerException
message.
Also, it doesn't look like you're using the Style mapboxStyle
parameter anywhere, so you can remove that from changeMapType()
.
来源:https://stackoverflow.com/questions/60320378/mapbox-getstyle-returns-null-when-changing-maptype