I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
in onLocationChanged method you can use location.getLatitude & location.getLongitude