简体   繁体   中英

LocationManager returns null longitude with getLastKnownLocation in Android

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM