0

I try to access the last known location in a Fragment as explained here

in my onCreate:

public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

in my onResume:

@Override
public void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
}

The Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

and the on Connected is called!!

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
    }
}

and the mLastLocation is always null. Everytime I try to call GetLastLocation() it returns null.

Any idea why?

Fabian
  • 2,693
  • 2
  • 21
  • 33
  • `getLastLocation()` has a high tendency to return null. It also does not request a new location, so even if you get a location, it could be very old, and not reflect the current location. Better to register a listener, even if you just unregister after you get the first `onLocationChanged()` callback. Take a look at the code in this answer, it's a very stripped down and basic implementation of registering a location listener: http://stackoverflow.com/questions/30191047/access-coarse-location-permission-gives-a-cell-tower-precision-on-android/30315009#30315009 – Daniel Nugent Jun 01 '15 at 22:11

1 Answers1

0

I never tried that approach, I usually create a LocationProvider that implements LocationsSource and LocationListener. Here's an example that may help you with this approach: How to get My Location changed event with Google Maps android API v2?

Community
  • 1
  • 1
GuilhE
  • 11,591
  • 16
  • 75
  • 116