当我从计时器调用此函数时,为什么这会尝试抛出数组我们的绑定异常。
如何解决此查询。在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;
}
答案 0 :(得分:1)
addresses
可以为空(与null不同但你无法得到第一项)
将if(addresses != null)
替换为if(addresses != null && !addresses.isEmpty())
答案 1 :(得分:0)
来自文档:
返回Address对象列表。如果未找到匹配项或没有可用的后端服务,则返回null或空列表。
所以返回一个包含0个对象的新ArrayList。你需要检查:
if(addresses != null && addresses.size() > 0) {
答案 2 :(得分:0)
由于地址列表已初始化,因此可能为空,但不为空。
if(addresses != null && !adresses.isEmpty())