5

The application i'm working on, works properly sometimes but some other times it gives me this error

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

And sometimes this error :

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

even though the onConnected() function is called. I moved the calling of buildGoogleApiClient() to the begining ofonCreate() here is my code:

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

calling the methods in onCreate():

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

but it keeps giving the same error sometimes, any idea why this happens?!

2 Answers2

0

You should not call loc.createLocationRequest(); immediate after you call loc.buildGoogleApiClient(); Instead you call loc.createLocationRequest() in onConected() of ApiCLient. loc.createLocationRequest() requires the GoogleApiClient to be connected by the time it is called.

For that matter, you should call any API that needs APiCLient connected in onConnected(). This way you avoid ApiClient connect exceptions while you use them.

ppreetikaa
  • 1,149
  • 2
  • 15
  • 22
cgr
  • 4,578
  • 2
  • 28
  • 52
  • A down vote, good. I would like to hear you what was wrong in the answer so I can correct it and even people would why..otherwise it mislead. If you can not take your vote. – cgr Sep 12 '16 at 09:03
0

This is coming late but for whoever it might be useful for:

  1. Move loc.buildGoogleApiClient(); to the onCreate method.
  2. Move loc.createLocationRequest(); to the onConnected method.
djubreel
  • 5
  • 1
  • 2