我正在尝试获取国家、州、城市、Pincode、子区域、地址的详细信息。但有时它会返回 City 为 null 或 SubRegion 为 null。这里附有图像
这是我的代码..
String locationCountry = "", locationState = "", locationCity = "", locationPincode = "", locationSubRegion = "", locationAddress = "";
Geocoder gCoder;
List<Address> addresses;
double latitude = 0, longitude = 0;
GPStracker g = new GPStracker(getApplicationContext());
Location l = g.getLocation();
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}else {
l = g.getLocation();
}
gCoder = new Geocoder(this, Locale.getDefault());
try {
addresses = gCoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
locationCountry = addresses.get(0).getCountryName();
locationState = addresses.get(0).getAdminArea();
locationCity = addresses.get(0).getLocality();
locationPincode = addresses.get(0).getPostalCode();
locationSubRegion = addresses.get(0).getSubLocality();
locationAddress = addresses.get(0).getAddressLine(0);
}
} catch (Exception e) {
}
最佳答案
Geo coder API 将根据纬度返回值,如果 API 数据库没有这些值(城市,那么它将仅返回 NULL,据我所知,您对此无能为力。您必须处理这些优雅地处理案例,这样您的应用就不会崩溃。
处理这些情况包括您必须使用 if
条件进行检查,以确定特定值是否为 null 或者它具有某个值,因为如果您在代码中的某个位置使用任何值而不检查 if该值为 Null,那么每当该特定值为 Null 时,应用程序可能会崩溃。
关于java - GeoCoder 将其中一个值返回为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967195/