Search code examples
androidgoogle-apionactivityresult

Why is GoogleApiClient disconnected when I try to access in OnActivityResult but not elsewhere?


When I call in the onActivityResult in a fragment, the GoogleApiClient I have in the parent activity is "not connected".

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Constants.REQUEST_PLACE_PICKER) {

        if (resultCode == Activity.RESULT_OK) {
            /* User has picked a place, extract data.
               Data is extracted from the returned intent by retrieving a Place object from
               the PlacePicker.
             */
            final Place place = PlacePicker.getPlace(data, getActivity());

            SharedPreferences prefs = getActivity().getSharedPreferences(Constants.SHARED_PREFS, Context.MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("address"+id, address.toString()).commit();
            editor.putString("name"+id, name.toString()).commit();
            Log.d(TAG, "Just picked a location, id=" + id);

            ((AllinOneActivity getActivity()).addGeofenceFromListposition(id); 
     getActivity()).addGeofencesButtonHandler(); // <-- This code that checks mGoogleCLientApi.connected()


            mRecyclerView.setAdapter(new LocationListAdapter(getGymLocations(), mListener, this));
        } else {
            Log.d(TAG, "resultCode is wrong " + "resultCode");

        }

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

However if I do the same thing in a button in the same fragment class, the thing is connected.

    //in onCreateView
    mFab = (FloatingActionButton) view.findViewById(R.id.fab);
    mFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mListener.onListFragmentInteraction(); //<-- Work fine!

        }
    });

AFAIK this should be calling the same activity, so why is the client disconnected in the first one but not the second?

//In parent Activity
public void onListFragmentInteraction(){
    addGeofencesButtonHandler();
}
public void addGeofencesButtonHandler() {
    Log.d(TAG, "Adding geoFencesButtonHandler click");
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, "not connected in addgeofence", Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                // The GeofenceRequest object.
                getGeofencingRequest(),
                // A pending intent that that is reused when calling removeGeofences(). This
                // pending intent is used to generate an intent when a matched geofence
                // transition is observed.
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
        logSecurityException(securityException);
    }
}

protected void onStart() {
        super.onStart();
    mGoogleApiClient.connect();

}

protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();

}

Solution

  • When you connect your GoogleApiClient, it doesn't become connected immediately. You have to register connection callback listeners to know when the connect is actually complete.

    In your case, what's happening is that onActivityResult() is being called by Android before your connect from onStart() is complete. onActivityResult() gets called between onStart() and onResume(), but you can't assume the client connect is finished by the time onActivityResult() is called.

    What you need to do instead is remember the result from onActivityResult() in a member variable, then check that value in your connection listener to know when it's safe to use your GoogleApiClient object with that data.