Google Api Client sometime NULL in onConnected

quangson91 picture quangson91 · Apr 14, 2015 · Viewed 12.1k times · Source

I implement GoogleApiClient as bellow:

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, 0 /* clientId */, this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .addConnectionCallbacks(this)
                .build();

But in onConnected method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error:

  java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0

Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL).

Thanks!

Update

My problem now solved after I try use latest version of play-service.

Thanks everybody for help.

Answer

Ben Faingold picture Ben Faingold · May 23, 2015

I had the same problem. All I did to solve it is remove .enableAutoManage(this, 0 /* clientId */, this) because it just doesn't work properly from what I assumed. Then, override these methods in your activity:

@Override
public void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}

@Override
public void onStop() {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
    super.onStop();
}

Technically, that is what .enableAutoManage(this, 0 /* clientId */, this) was supposed to do, except that now, everything works as it should.