[英]Location value returning null android
我正在嘗試獲取用戶的位置,並且我有這種方法
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;
}
我有另一種方法,該方法將根據location
變量的經度和緯度將圓形對象居中
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()))
);
}
}
現在,此代碼以前可以在具有和不具有GPS的設備上使用。 誰能告訴我為什么userLocation
拋出NullPointerException
嗎?
請記住, getLastKnownLocation
有時可能返回null
(例如,如果提供程序當前處於禁用狀態,或者沒有最后一個已知位置),那么您應始終檢查此方法的結果:
Location location = locManager.getLastKnownLocation(provider);
if (location == null){
//handle this case
//return location with some default coordinates, for example
}
return location;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.