I am using geofencing in my app. Whenever I try to add geofences, I get the following error.
IllegalStateException: GoogleApiClient is not connected yet
In AppCompatActivity onCreate method I define the client
/* Create a new google api client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
and in my onStart method I connect to it ensuring that it is not null
/* Connect to the API client */
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
but still it gives that error.
My AppCompatActivity implements OnMapReadyCallback and ResultCallback interfaces among others
for which I have an overridden method
@Override
public void onMapReady(GoogleMap googleMap) {}
The onMapReady method contains this lines of code
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(MapsActivity.this);
I have defined getGeofencingRequest and getGeofencingPendingIntent private methods and overridden the onResult method in ResultCallback.
I have spent hours and hours on this error and can't seem to get headway. The app executes normally until the AppCompatActivity is started. onCreate happens normally, onStart happens normally as well.
I think there are two possibilities for this error:
The onMapReady method is being called before onStart (unlikely)
The onStop method disconnects the client before it is available to the onMapReady method
Regardless some resolution to the error will be appreciated.
Link to full gist is below: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac
I found the answer to my own question.
Apparently, the google API client connection is separate to the Google Map connection. API client is specifically for location services.
As such I needed to set up geofencing after the API connection has been established.
So I moved all of my geofencing code inside of onConnected as well.
@Override
public void onConnected(Bundle savedInstanceState) { }
That solved the issue.
Take a look at the updated gist: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac