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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With