-1

So as the title says, I'm following the code found on the Android developer site and attempting to get the latitude and longitude of my current location. I'm using Android Studio and an emulator. I have no idea why my code is passing null when I use getLatitude() and getLongitude() - I thought I followed the code as specified.

Thanks!

(What's needed of the class) HomePage.java:

public void onConnected(@Nullable Bundle bundle) {
    if (location == null){
        declareLocation();
    }
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    SharedPreferences sharedPreferences = getSharedPreferences("example.com.musicapptest", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putLong("latitude", Double.doubleToLongBits(latitude));
    editor.putLong("longitude", Double.doubleToLongBits(longitude));
}
private Location declareLocation(){
    try{
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }
    catch (SecurityException e){
        e.printStackTrace();
    }
    return location;
}
  • Possible duplicate of [LocationClient getLastLocation() return null](http://stackoverflow.com/questions/16830047/locationclient-getlastlocation-return-null) – Daniel Nugent Jul 16 '16 at 01:10

1 Answers1

0

A number of factors could be causing this. Is the ApiClient connected? Did you build correctly? If both of these are true, then location is not avaiable.

Quoting the reference:

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 can also use getLocationAvailability().isLocationAvailable() to find out whether null will be returned. If this method returns false, you need to request location updates using the requestLocationUpdates() method.

Regarding location updates, you can refer to this guide: https://developer.android.com/training/location/index.html

Community
  • 1
  • 1