-1

当我从计时器调用此函数时,为什么尝试抛出绑定异常的数组。

我该如何解决这个查询。此代码在 run 函数之间调用。list<Address> addresses是超出范围的数组异常。告诉我一些解决此查询的方法

public String get_address(double latitude ,double longitude)
{
    String address = null;

    if(Geocoder.isPresent())
    {
        try{
            Geocoder geocoder2 = new Geocoder(mContext, Locale.getDefault());
              List<Address> addresses;
              addresses = geocoder2.getFromLocation(latitude, longitude, 2);
               if(addresses != null) {
                     Address returnedAddress = addresses.get(0);

                     StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                     for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                     strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    }
                     /*if(returnedAddress.getMaxAddressLineIndex() > 0){
                         strReturnedAddress.append(returnedAddress.getAddressLine(0) + ", ");
                       }

                       strReturnedAddress.append(returnedAddress.getLocality() + ", ");
                       strReturnedAddress.append(returnedAddress.getCountryName());
                     */

                     address=strReturnedAddress.toString();
                     }
                     else{
                     address="No Address returned!";
                     }
               //return address;

        }
        catch(Exception e)
        {
            Log.e("MyAPP", "Reverse geo lookup failed", e);
                address="reverse geo look up failed";
             //return address;
        }

    }
    else
    {
        address="Geocoder is not present";
        //return address;
    }
    return address;
}
4

3 回答 3

1

addresses可以为空(与 null 不同,但您无法获取第一项)

替换if(addresses != null)if(addresses != null && !addresses.isEmpty())

于 2013-02-11T10:33:11.257 回答
0

从文档:

返回地址对象的列表。如果未找到匹配项或没有可用的后端服务,则返回 null 或空列表。

返回一个带有 0 个对象的新 ArrayList 也是如此。您需要检查:

if(addresses != null && addresses.size() > 0) {
于 2013-02-11T10:33:57.173 回答
0

由于地址列表已初始化,因此可能为空,但不为空。

if(addresses != null && !adresses.isEmpty())
于 2013-02-11T10:34:34.963 回答