GoogleApiClient is not connected yet.

The application I'm working on sometimes works fine, but sometimes it gives me this error

FATAL EXCEPTION: java.lang.RuntimeException: cannot pause {com.example.dell.locationapi / com.example.dell.locationapi.MainActivity}: java.lang.IllegalStateException: GoogleApiClient is not yet connected.

And sometimes this error:

java.lang.IllegalStateException: GoogleApiClient is not yet connected.

even if the onConnected() function is onConnected() . I translated the call to buildGoogleApiClient() to the beginning of onCreate() , here is my code:

 protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API).build(); } 

calling methods in onCreate() :

  loc = new MyLocation(MainActivity.this); if (loc.checkPlayServices()) { loc.buildGoogleApiClient(); loc.createLocationRequest(); } 

but sometimes he continues to give the same error, any idea why this is happening ?!

+5
source share
2 answers

You should not call loc.createLocationRequest (); right after calling loc.buildGoogleApiClient (); Instead, you call loc.createLocationRequest () on the onConected () ApiCLient. loc.createLocationRequest () requires GoogleApiClient to connect at the time it is called.

In this case, you must call any API for which APiCLient is connected in onConnected (). This way you avoid ApiClient connect exceptions while using them.

0
source

This is delayed, but for those who may find it useful:

  • Move loc.buildGoogleApiClient(); into the onCreate method.
  • Move loc.createLocationRequest(); into the onConnected method.
0
source

All Articles