我正在尝试从纬度和经度中获取用户的地址,如下所示:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat =location.getLatitude();
lon = location.getLongitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
try{
Geocoder geocoder;
geocoder = new Geocoder(this, Locale.getDefault());
addresses=(geocoder.getFromLocation(lat, lon, 1));
}catch(IOException e){
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
TextView tv = (TextView) findViewById(R.id.tv3);
tv.setText(address+"\n"+city+"\n"+country);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
每次我运行它时,我都会在“String address =addresses.get(0).getAddressLine(0);”的行上收到错误“IndexOutOfBoundsException: Invalid index 0, size is 0”。我了解该错误意味着我正在尝试访问不存在的内容,但我不确定是什么原因造成的。我一直在寻找获得地址的最佳方式,这就是我发现的,但它可能不是最有效或最好的方式。有什么建议么?