java - GeoCoder 将其中一个值返回为 null

标签 java android geolocation

我正在尝试获取国家、州、城市、Pincode、子区域、地址的详细信息。但有时它会返回 City 为 null 或 SubRegion 为 null。这里附有图像 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) {
            }

最佳答案

Geo coder API 将根据纬度返回值,如果 API 数据库没有这些值(城市,那么它将仅返回 NULL,据我所知,您对此无能为力。您必须处理这些优雅地处理案例,这样您的应用就不会崩溃。

处理这些情况包括您必须使用 if 条件进行检查,以确定特定值是否为 null 或者它具有某个值,因为如果您在代码中的某个位置使用任何值而不检查 if该值为 Null,那么每当该特定值为 Null 时,应用程序可能会崩溃。

关于java - GeoCoder 将其中一个值返回为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967195/

相关文章:

JAVA展示13套

java - 空点异常 - ImageLoader

java - Google map .getMap() 已弃用

java - 安卓 : how to get the walking distance between two geo coordinates?

google-maps - 有没有办法在不让用户安装 Google Gears 的情况下获取用户位置?

javascript - 有什么方法可以自定义 Google 的自动完成地址结果吗?

java - 如何防止接口(interface)在继承类中实现?

java - JSF 2.0 - 使用调试器逐步完成生命周期中每个阶段的方法?

java - 如何退出 NetBeans 平台 GUI 应用程序?

android - finishActivity() 的可能用例是什么