Search code examples
androidfusedlocationproviderapi

Android LocationServices.FusedLocationApi.getLastLocation returns "null"


I have already read solutions to this question in other threads but I do not seem to understand why does it return null. I have used the same snippet provided in the google developers site: https://developer.android.com/training/location/retrieve-current.html

I am using the following code in my activity to get the user's current location:

public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buildGoogleApiClient();
}
@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();
}
@Override
public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
}

}

If "mLastLocation" is always null, how can we write code to get the user's current location?


Solution

  • The documentation states (right at the bottom of the article):

    The location object returned may be null in rare cases when the location is not available.

    This can occur when a device has Location Services disabled, or the device is in airplane mode. It also seems to occur when a location hasn't been requested in a long time.