无法使用地理编码器,给出了未处理的类型IOException



这是代码

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                Geocoder gcd = new Geocoder(context, Locale.getDefault());
                List<Address> addresses = **gcd.getFromLocation(latitude, longitude, 1);**

给出错误的部分用星号突出显示。

谢谢。

如果网络不可用或出现任何其他I/O问题,则getFromLocation()抛出IOException

http://developer.android.com/reference/android/location/Geocoder.html#getFromLocation(双,双,int)

要解决此问题,请用try/catch块围绕它:

try {
    List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
}
catch (IOException e) {
    e.printStackTrace();
}

除了Ken WOlfs的回答外,您还必须检查设备上是否有GeoCoder服务。

"Geocoder类需要一个没有包含在核心android框架中的后端服务。如果平台中没有后端服务,Geocoder查询方法将返回一个空列表。使用isPresent()方法来确定是否存在Geocoder实现。"-谷歌

所以你的代码应该是这样的:

if(Geocoder.isPresent()){
    Geocoder gcd = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
    } catch (IOException e) { e.printStackTrace(); }
}

最新更新