I have a class object which retrieves the users latitude and longitude. In my UI thread I create the object in the onCreate method that creates the Activity:
userLocation = new UserLocation(this);
Here is the class snippet:
public UserLocation(Context mContext) {
//Pass parameter to class field:
this.mContext = mContext;
//Fetch the user's location:
fetchUserLocation();
}
public void fetchUserLocation() {
// Acquire a reference to the system Location Manager:
LocationManager locationManager = (LocationManager)this.mContext.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Manage the data recieved:
makeUseOfLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private void makeUseOfLocation(Location location) {
//Split the data of the location object:
userLatitude = location.getLatitude();
userLongitude = location.getLongitude();
}
/**
* @return userLatitude
*/
public double getLatitude() {
return userLatitude;
}
/**
* @return userLongitude
*/
public double getLongitude() {
return userLongitude;
}
Now back in the main thread, when a button is pressed, the latitude and longitude is collected:
// GET THE LATITUDE AND LONGITUDE OF THE USER:
currentLatitude = userLocation.getLatitude();
currentLongitude = userLocation.getLongitude();
Now for say I launch the application, if I press that button right away, the values received are 0.0 for both latitude and longitude.
But, if I launch the application and wait 4-5 seconds then press the button, correct values are then received.
Can anyone tell me the cause of this behavior?
I noticed it when I was writing a method that when the user launches the application if a field is null, then collect latitude and longitude. Well this in turn returns the unfavored 0.0 value.
Thanks!
Can anyone tell me the cause of this behavior?
Well yes - presumably when it's showing 0, 0, onLocationChanged
hasn't been called yet - because the location isn't known immediately. You've requested that the location manager calls you back when it knows the location - that's not the same as getting the location immediately.
If you don't want to report the location to the user before it's known, you should remember whether or not onLocationChanged
has been called (or potentially even when it was last called, to avoid showing stale data).
See more on this question at Stackoverflow