Reputation: 6839
Every once in a while my app will crash when it attempts to get the user location. Unfortunetley I fo not have the error, because it has never happened when I am plugged into my computer...
I am using this to get my user location:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
I am thinking sometimes this might be null? If so how can I fix this force close?
Upvotes: 0
Views: 201
Reputation: 18231
I would recommend not rolling your own GPS.. Use Fused Location Provider:
Here is an example : http://www.kpbird.com/2013/06/fused-location-provider-example.html?m=1
Upvotes: 0
Reputation: 1746
Always use Try & catch block when there's a chance of Exception.You will get NullPointerException if location returns null.
try {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
} catch (Exception e) {
}
Upvotes: 0
Reputation: 2486
Its not force closing while getting location.. its getting force closed while assigning longitude and latitude.. put an if(location!=null)
before asigning the values
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//location might be null so
if(location != null)
{
double longitude = location.getLongitude();
double latitude = location.getLatitude();
}
Upvotes: 2
Reputation: 22008
You have no guarantee that location won't be null (there might not be a last known location), so you'll have a NullPointerException in
location.getLongitude()
Check that location != null before proceeding.
Upvotes: 0