gpt4 book ai didi

java - 位置值返回 null android

转载 作者:行者123 更新时间:2023-12-01 13:00:31 25 4
gpt4 key购买 nike

我正在尝试获取用户的位置,我有这个方法

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;

关于java - 位置值返回 null android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com