Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException - location is null?

I am getting a nullpointerexception on this line:

double latitude = location.getLatitude();

Here is the block of code that is causing me issues:

//Get the current location
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);

//Zooms into the current location when the activity is started
double latitude = location.getLatitude();
double longitude = location.getLongitude();

How am I getting a nullpointerexception when I'm intializing my Location variable and LocationManager variable? What is wrong with my code?

like image 638
user268397 Avatar asked Aug 10 '26 16:08

user268397


1 Answers

If nothing on the phone is actually listening to the location updates then the phone will not update the last known location. In this case, if the value is too out of date it will return null (otherwise it could return some very stale data). If you want to ensure that you get a location you need to register for updates yourself. Then, after the first update occurs you can call getLastKnownLocation whenever you want.

like image 69
Gabe Sechan Avatar answered Aug 13 '26 08:08

Gabe Sechan