2

I have a code that is supposed to return the user location but the Longitude keeps returning null and as a result my app keeps crashing. How do I prevent this?

//get the user longitude and latitude
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

Geocoder geocoder;  //return meaningful data from user location
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
Tunaki
  • 125,519
  • 44
  • 317
  • 399
Blaze
  • 2,159
  • 10
  • 35
  • 77

1 Answers1

7

Add a check.

if (location != null) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

as for why it's not returning a value, you'd need to add some logging.

For a more complete solution try this:

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);
        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get destination from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                //  Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(
                            LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    // Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(
                                LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}

In this implementation, this is a method from a class, that I call from my activities. Along with code needed to release resources after they are no longer needed.

for example:

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(LocFinder.this);
    }
}

Disclaimer Please note this is only part of the code needed, and to assist in implementing location services. Resources need to be released when not being used and the use of location services, as with all other aspects of a project need to be managed within the program flow of the overall application.

Have a look at Getting the Last Known Location or Android Location API - Tutorial or Android - Location Based Services for a fuller implementation of location services.

  • I am having error on this line locationManager = (LocationManager) mContext – Blaze May 24 '16 at 15:37
  • what values do I use here MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, – Blaze May 24 '16 at 16:39
  • What's the point of calling `requestLocationUpdates()` if you don't implement an `onLocationChanged()` method to receive the location updates? GPS at least will have a several seconds delay before the location is updated so calling `getLastKnownLocation()` right after that is not going to give you the latest up-to-date location. And not only that, but the location updates are not cancelled, so the GPS is kept active and it's draining the battery whether you call this method again later or not. This is NOT a good implementation for getting an up-to-date location and should not be upvoted. – Markus Kauppinen May 24 '16 at 17:31