- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一种方法可以在 map 上显示设备的当前位置。我使用 FusedLocationProviderClient
因为它似乎是最准确的。
在 currentLocation.getLatitude()
上,我收到警告:
Method invocation may produce java.Lang.NullPointerException
如何避免这种风险?为什么它只与 currentLocation.getLatitude() 相关,而不与 currentLocation.getLongitude()
相关?
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(task -> {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
}else{
Log.d(TAG, "onComplete: current location is null");
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
最佳答案
IDE 在显示有关代码的信息时可能会很奇怪或被误解,但我向您保证它适用于 getLongitude() 以及实例方法或实例成员的任何其他调用,因为位置可能为 null。
public Task getLastLocation ()
Returns the best most recent location currently available.If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.
This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.
所以即使任务成功,任务的结果也可能为空。这意味着您需要在使用之前检查 location 是否为空。
关于java - 避免方法调用 getLatitude 可能会产生 java.Lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56158488/
java.lang.Throwable 的哪些子类可能被空语句抛出? 通过短语“空语句”,我指的是“无”、“分号”和“分号”: // .... A(); B(); C(); try { //
我是一名优秀的程序员,十分优秀!