'java.io.IOException: grpc failed

When I use call getFromLocationName I get an IOException with description "grpc failed".

Code that's ran

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    try {
        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
        List<Address> listAdresses = geocoder.getFromLocationName("London", 10);
        Log.i("PlaceInfo", listAdresses.get(0).toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Error the console outputs:

07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: java.io.IOException: grpc failed
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.location.Geocoder.getFromLocationName(Geocoder.java:178)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at co.siqve.maplocationdemo.MapsActivity.onMapReady(MapsActivity.java:70)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.google.android.gms.maps.zzaj.zza(Unknown Source)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.os.Binder.transact(Binder.java:499)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.google.android.gms.maps.internal.aq.a(:com.google.android.gms.DynamiteModulesB:5)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.google.maps.api.android.lib6.impl.bb.run(:com.google.android.gms.DynamiteModulesB:5)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.os.Looper.loop(Looper.java:154)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Android SDK Version (API Level): 25

Android Studio plugins are up to date.

Thanks in advance!

EDIT:

Problem seems to be fixed now, here is my solution.



Solution 1:[1]

I can reproduce this issue (java.io.IOException: grpc failed), when there is no Internet connection on my real device.

Solution 2:[2]

Like Google writes, You should not call this method on UI thread

https://developer.android.com/training/location/display-address#java

I fixed this issue by running this operation in a new Thread, and then if I need to update some UI view I'll do it on runOnUiThread

Solution 3:[3]

May be you are having this issue in genymotion and android studio emulator only. I faced same issue with genymotion and android studio emulator and then i checked it in android real device. It's working good for me. Did you check it in real device?

Solution 4:[4]

This issue appeared for me (even though I make the request on a background thread), but in the Android Studio emulator only. A strange workaround that fixes it for me is to turn on and then turn off airplane mode!

Solution 5:[5]

I face this issue on Android 4.4.2 device several times. For me the solution is simply to restart the handset. No code update no Android studio uninstall.

Solution 6:[6]

This was happening also on my Samsung S7 Edge phone with Oreo installed. It only happened when I had an airplane mode on (not always - means something might have been cached at some points). I didn't explore the guts of Geocoder but I assume it requires some sort connectivity to get the information (that would also explain why this is happening so often on emulators). For me the solution was to check the network connectivity status and call this only when status != NETWORK_STATUS_NOT_CONNECTED.

For this you can implement a broadcast receiver, that will listen to any status changes on network.

Register receiver

IntentFilter networkFilter = new IntentFilter();
networkFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
getActivity().registerReceiver(NetworkChangeReceiver, networkFilter);

Setup broadcast receiver to handle the broadcast

private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(final Context context, final Intent intent) {
    int status = NetworkUtil.getConnectivityStatusString(context);

    if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
    } else {
      // do your stuff with geocoder here
    }
  }
};

Solution 7:[7]

As of August 2019, I still get this from time to time when I'm snooping my own http traffic with a proxy. Turn it off and problem gone.

Solution 8:[8]

SomeTimes Geocoder failed when latitude and longitude contain above 3 decimal places, or it may be said that Geocoder can not decode every latitude and longitude. you need to limit latitude and longitude upto 3 decimal places. complete code

        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(3);

        double lat = Double.parseDouble(df.format(currentUserLocation.latitude));
        double lon = 
        Double.parseDouble(df.format(currentUserLocation.longitude));
        Geocoder geocoder = new Geocoder(myContext, Locale.getDefault());

        List<Address> addresses  = geocoder.getFromLocation(lat,lon, 1);

        String cityName = addresses.get(0).getLocality();

Solution 9:[9]

Today (2017-09-16) my Android Studio (2.3.3) got an update for Google Play services to revision 44. The issue was fixed afterwards. No code or setup changes from my side.

Solution 10:[10]

Although pretty late on the issue, here is an answer for Kotlin users.

I stumbled upon this java.io.IOException: grpc failed error whilst using Geocoder's getFromLocation function. I have been using a Google Pixel 2 as my test device (running Android 9).

There are 3 things to make sure of:

  1. As noted by many here (and in the Android documentation here), anything relating to Geocoder needs to be done apart from the main thread of your app. To support my claim, here is a quote from the Android documentation: "The method is synchronous and may take a long time to do its work, so you should not call it from the main, user interface (UI) thread of your app."

Now, it is best to use IntentService for this task like the official documentation has given an example of. However, this person tried it with an AsyncTask in Java and it worked just fine (note that their task with geocoder was a lot less intensive). Therefore, I highly recommend using Anko's doAsync method and implement any code regarding Geocoder within it.

  1. If possible, use a physical device instead of an emulator. The emulator on Android Studio gave me a lot of trouble and was not giving me the error information I needed to really debug the problem.

  2. Reinstall your app on your physical device and Invalidate Caches/Restart your project several times.

Also make sure you have good network connection and it is enabled on your device.

Solution 11:[11]

I think this depends on the location of the device. because google map sometimes not working properly in some area. I'm from Iran and I also had this problem on real device and emulator. After a while go with this problem, I used a vpn application and it worked on the real device and emulator. because vpn application changed my ip address.

Solution 12:[12]

after some research figure out how to solve this , in my case all ways like put code in new Thread or use GeocodingApi not work , i just make sure

play-services-base

and

play-services-location

have same version like below :

implementation 'com.google.android.gms:play-services-base:17.1.0'

implementation 'com.google.android.gms:play-services-location:17.1.0'

Solution 13:[13]

I finally got this to work by using the following configuration for version 25 SDK, Build Tools and API emulator.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example..."
        minSdkVersion 15
        targetSdkVersion 25

Also using Google API version 11.0.2.

Solution 14:[14]

AOA! turn the accuracy Mode of device Gps to (only gps) instant of other option and then try......

worked for mesettings are like this , i am postie you can also find them on emulators

Solution 15:[15]

I faced this issue while getting Addresses List using geocoder.getFromLocation() method, the problem is that getting addresses list from latitude,longitude takes time or on some slow devices it takes more time and, also sometimes it give me the java-io-ioexception-grpc-failed.

I fix this problem using Rx Java.

public class AsyncGeocoder {

private final Geocoder geocoder;

public AsyncGeocoder(Context context) {
    geocoder = new Geocoder(context);
}

public Disposable reverseGeocode(double lat, double lng, Callback callback) {
    return Observable.fromCallable(() -> {
        try {
            return geocoder.getFromLocation(lat, lng, 1);
        } catch (Exception e) {
            AppLogger.d("throwable,", new Gson().toJson(e));
            e.printStackTrace();
        }
        return false;
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(result -> {
                //Use result for something
                AppLogger.d("throwable,", new Gson().toJson(result));

                callback.success((Address) ((ArrayList) result).get(0));
            }, throwable -> AppLogger.d("throwable,", new Gson().toJson(throwable)));
}

public interface Callback {
    void success(Address address);

    void failure(Throwable e);
}
}

Calling Position

mViewModel.getLocation(asyncGeocoder, getLat(), getLng(), this);

ViewModel Method

public void getLocation(AsyncGeocoder geocoder, Double lat, Double lng, AsyncGeocoder.Callback callback) {
        getCompositeDisposable().add(geocoder.reverseGeocode(lat, lng, callback));
    }

Solution 16:[16]

This issue has already been reported, you can find other stack posts talking about it. Here is a comment on google issue with some of the different way geocoder crashes. I advise you to surround your part of code with try and catch, so your application doesn't stop.

Solution 17:[17]

In Wifi connection worked fine but in 3g or 4g connection is fail.

Using proxy

Solution 18:[18]

From my experience, I can say this error is thrown by the Geocoder's getFromLocation() method. So don't do the following:

  • Do not call this method on main thread. This will freeze the UI and if anything which depends on the result of this method will crash. Handle this case.
  • When there's no internet connection, again, the IOExeption will be thrown. Again, anything depending on the result of this method will crash. Handle this case.

Solution 19:[19]

In my case I just turned on (permission granted) the Position from app permission setting.

Solution 20:[20]

It works for me if introduce Geocoder as singleton for application rather than create it every time. Make sure to call Geocoder.getFromLocationName() from worker thread.

For example:

class Application {
    private val geoCoder = Geocoder(context, Locale.getDefault())
    ...
}

class SomeClass {

    @WorkerThread
    fun doSmth(){
       application.geoCoder.getFromLocationName("London", 10)
       ...
    }
}

Solution 21:[21]

I experienced the same issue and didn't know where the problem was. At all... Until recently, I started noticing that this problem appeared on a real device, when I had configured a proxy. When I used charles on MAC there was no issue with that, but when I started using MITM on Linux, this issue starting popping every time, without exception. Probably need to configure MITM additionally. But the bottom line is, if you turn off your proxy, you should be fine.

So look into that maybe.

Solution 22:[22]

I seem to have fixed this issue by opening the top toolbar of the phone and just swithing between wifi and network, i guess the operating memory on all virtual devices is set to 2GB RAM and finding location is just using too much therefore, I saw a skip in frames and location not being able to search. So if it is dropping this error, just switch from Wifi to Network and backwards.

Solution 23:[23]

In my case, I deleted the AVD and re-installed it and everything was OK.

Solution 24:[24]

Hi I had the "grpc failed" error after returning to an older project/test phone.

My code was calling the getFromLocation() method and just failing. reading and playing around for a few hours, I thought I would check if google maps would work, it showed my location on a blank map, wifi was switched off, so I turned WIFI on, Map worked fine.

Retested app, and voila my getFromLocation() method is working, so must have had something sticky in the location services area....

Solution 25:[25]

List<Address> addresses  = geocoder.getFromLocation(lat,lon, 1);

Size of addresses would usually be 0. This may be as a result of failure to peak addresses hence marking them as "Unknown" or "default" could be an option

Solution 26:[26]

I got the same error when the search term was empty. Once I made sure that it is not empty the error disappeared. By search term I'm referring to the first argument of getFromLocationName method.