我正在开发一个应用程序,我想在地图上显示多个标记。 (标记来自数据库(dynamodb),值都在“STRING”而不是两倍)。在将double转换为所有“纬度和经度”的字符串之后,我得到java.lang.NumberFormatException的异常:无效的double:“n / a”和app崩溃。因为在表格中,一个lat长显示“na”。 (如图所示)
我卡住了,不知道如何处理这个空值。我应该检查一下还是什么?提前致谢
((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
final LatLng israel = new LatLng(31.0461, 34.8516);
googleMap.addMarker(new MarkerOptions().position(israel).title("israel"));
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
CameraPosition camPos = new CameraPosition.Builder().target(new LatLng(31.0461, 34.8516)).zoom(8).tilt(70).build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
googleMap.animateCamera(camUpd3);
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
DDBExecutor.getInstance().getAllSettlements(mContext, new DDBExecutor.OnResponseListener() {
@Override
public void onResponse(Object result, String message) {
List<SettlementsTable> lstSettlements = new ArrayList<>();
lstSettlements.addAll((List<SettlementsTable>) result);
for (SettlementsTable table : lstSettlements){
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(table.getX()), Double.parseDouble(table.getY()))));
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(israel);
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
mMap.moveCamera(cu);
mMap.animateCamera(CameraUpdateFactory.zoomTo(8), 2000, null);
try {
KmlLayer kmlLayer = new KmlLayer(googleMap, R.raw.settlements, getApplicationContext());
kmlLayer.addLayerToMap();
KmlLayer kmlLayer1 = new KmlLayer(googleMap, R.raw.outposts, getApplicationContext());
kmlLayer1.addLayerToMap();
KmlLayer kmlLayer2 = new KmlLayer(googleMap, R.raw.settlements_in_pal_nghbrhd, getApplicationContext());
kmlLayer2.addLayerToMap();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
答案 0 :(得分:4)
在@OnkarShelke给出的答案的catch块中,你可以 手动添加mMap中的默认值而不是简单 处理异常。像:
mMap.add(new MarkerOptions().position(new LatLng(10.5,1.2));
// 10.5 and 1.2 could be your default values.
或者因为您已经知道导致错误的错误值(n / a)
例外,您可以在尝试添加到mMap
之前检查该值。像:
for (SettlementsTable table : lstSettlements){
if (table.getX().equalsIgnoreCase("n/a") || table.getY().equalsIgnoreCase("n/a")) {
// do something like add default values
} else {
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(table.getX()), Double.parseDouble(table.getY()))));
}
}
答案 1 :(得分:3)
环绕尝试捕捉
try {
mMap.addMarker(new MarkerOptions().position(new
LatLng(Double.parseDouble(table.getX()),
Double.parseDouble(table.getY()))));
} catch (NumberFormatException ex){
//do anything when exception occurs
}
答案 2 :(得分:2)
包含SettlementsTable对象的第一个过滤器列表,这样当对象字段中有n / a字符串时,不要将其添加到您要提供给Marker对象进行绘图的Arraylist对象。