android / location-samples

Multiple samples showing the best practices in location APIs on Android.
Apache License 2.0
2.7k stars 2.77k forks source link

Geocode for java #310

Open panjisadewo opened 1 year ago

panjisadewo commented 1 year ago

I try geocode but i has error like this. java.io.IOException: Service not Available 2022-10-18 12:30:10.785 4101-4101/? W/System.err: at android.location.Geocoder.getFromLocationName(Geocoder.java:178)

This is my code

    Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
    List<Address> addresses;;
    try {
        addresses = geocoder.getFromLocation(-6.193479061, 106.848579406, 10);
        if(addresses.size() > 0){
            String cityName = addresses.get(0).getCountryName();
            String stateName = addresses.get(0).getAddressLine(1);
            String countryName = addresses.get(0).getAddressLine(2);
            Toast.makeText(getActivity(), addresses.size(), Toast.LENGTH_LONG);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
SweetD3v commented 1 year ago

You need to check if the service is available or not on the device like this,

if (GeoCoder.isPresent()) {
    //TODO Get the address
}