Reputation: 670
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?
Upvotes: 2
Views: 1455
Reputation: 41
You might have to check the location settings of the device you are using. I had the same problem. My location settings were set to use gps only, I switched it to high precision which use wifi, gps and mobile services to determine your location. This solved the problem for me. Hope it helps
Upvotes: 1
Reputation: 4066
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.
Upvotes: 1
Reputation: 179
read this solution:
private static GoogleApiClient mGoogleApiClient;
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
Upvotes: 0