错误
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0.
这是我的代码。
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Geocoder geocoder;
geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
if (city == null) {
Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapsActivity.this, "" + city, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
答案 0 :(得分:1)
GeoCoder
可能不会在所有情况下都返回结果,因为海洋或海洋可能没有地址。
在这种情况下,名为addresses
的结果列表将包含0个项目,但您仍尝试访问第一个项目。
你应该这样做:
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses.size() == 0) {
Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
return;
}
// ... rest of the code