GeoCoder返回值之一为null

时间:2018-10-24 10:55:08

标签: java android geolocation

我正在尝试获取Country,State,City,Pincode,SubRegion,Address的详细信息。但有时它返回City为空值或SubRegion为空值。此处附有图片enter image description here

这是我的代码。

 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) {
            }

1 个答案:

答案 0 :(得分:1)

Geo coder API将根据lat long返回值,如果API数据库中没有这些值(city,那么它将仅返回NULL,据我所知您对此无能为力。您必须处理这些的情况下,以确保您的应用不会崩溃。

处理这些情况包括必须使用if进行检查,条件是该特定值是null或具有某个值,因为如果您在代码中的某处使用了任何值而没有检查,并且该值是否为如果为null,则只要该特定值变为null,应用程序便可能崩溃。

相关问题