Ciao! I have an Activity that needs the current location so an user can see which objects are close to him.
Well, I'm going to crazy with GoogleApiClient, FusedLocation, callbacks and so on and the only result I get is that getLastLocation
returns null
.
My Activity implements GoogleApiClient.ConnectionCallbacks
and GoogleApiClient.OnConnectionFailedListener
.
In OnCreate
I call getLocation()
that is like this:
private void getLocation(){
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(60*1000);
locationRequest.setFastestInterval(10*1000);
mFusedLocationApi = LocationServices.FusedLocationApi;
gApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (gApiClient != null) {
gApiClient.connect();
}
}
I also have this:
@Override
protected void onStart() {
super.onStart();
if (gApiClient != null) {
gApiClient.connect();
}
}
@Override
protected void onStop() {
gApiClient.disconnect();
super.onStop();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.w("ADVSEARCH","Error on connection failed");
}
@Override
public void onConnectionSuspended(int i) {
Log.w("ADVSEARCH","Error on connection suspended");
}
@Override
public void onConnected(Bundle bundle) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//lastlocation = LocationServices.FusedLocationApi.getLastLocation(gApiClient);
mFusedLocationApi.requestLocationUpdates(gApiClient, locationRequest, new com.google.android.gms.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
lastlocation = location;
}
});
}
lastlocation = LocationServices.FusedLocationApi.getLastLocation(gApiClient);
}
And yes, in OnCreate
I check for permissions. Minimum API 16, Target API 25.
Every time I open the app the first time it crashes because I use distanceTo
on a null object. What am I missing? The more I search, the more I get confused.