I'm trying to get a user's location and I have this method
public Location getCurrentLocation() {
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
return location;
}
I have another method that will center a circle object based on the location
variable's latitude and longitude in this method
private void loadMapResources() {
userLocation = getCurrentLocation();
//DRAW CIRCLE HERE
if(userRadius != 0){
Circle radiusCircle = googleMap.addCircle(new CircleOptions()
.center(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.radius(userRadius)
.strokeWidth(4)
.strokeColor(Color.parseColor("#FF6699"))
.fillColor(Color.parseColor("#66F3F3F3"))
);
//SHOW USER ICON AT CURRENT LOCATION
BitmapDescriptor userIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_user);
googleMap.addMarker(new MarkerOptions()
.title("YOU ARE HERE")
.icon(userIcon)
.position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
);
}
}
Now this code has worked before on devices with and without GPS. Could anyone tell me why userLocation
is throwing a NullPointerException
?
Please keep in mind, that getLastKnownLocation
can sometimes return null
(for example, if provider is currently disabled or there is no last known location), so you should always check the result of this method:
Location location = locManager.getLastKnownLocation(provider);
if (location == null){
//handle this case
//return location with some default coordinates, for example
}
return location;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.