Question

I'm using the LocationClient to get the user location from the network (no gps). I instantiate the LocationClient during the creation of my fragment

 mLocationClient = new LocationClient(getActivity(), this, this);
 mLocationClient.connect();

And then later

  if (mLocationClient.isConnected())
  {
    currentLocation = mLocationClient.getLastLocation();
  }

I am sure that it is connected, but the getLastLocation() returns null always.

However, it works using the LocationManager.

    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

I know I could just use a listener for location updates, but I would like to understand why getLastLocation() always returns null.

Was it helpful?

Solution

Document says :-

public Location getLastLocation ()

Returns the best most recent location currently available. If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned. This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.

You have to use onLocationChange() method to get location:-

@Override
public void onLocationChanged(final Location location) {
      mCurrentLocation = location;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top