Reputation: 95
I am trying to get the location from the user but when I put the following request code for the location:
private void getLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
}
}
It crashes because it gets the mLastLocation
null
I call the function in the onResume()
method but with no success. But if I put it in a button click callback, it gets the location.
Is there any way to get the location once the application has loaded?
Upvotes: 0
Views: 371
Reputation: 4283
First you should check that you have the required permissions to make this request.
You should get user location after you are connected to Google's LocationServices API.
Then you should request location asynchronously using Task returned by FusedLocationProviderClient.getLastLocation()
Here is some code to help you out:
GoogleApiClient mGoogleApiClient;
private void getGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getName(), "Location permission not granted");
return;
}
Task task = mFusedLocationClient.getLastLocation();
task.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
Log.e(getClass().getName(), "onConnectionSuspended() ");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e(getClass().getName(), "Get location failure : " + connectionResult.getErrorMessage());
}
})
.build();
}
mGoogleApiClient.connect();
}
Simply call the method getGoogleApiClient() when you need location. Do make sure GPS location is activated on your device.
For more infos on this topic:
https://developer.android.com/training/location/retrieve-current.html
Upvotes: 1