我有一种方法可以在 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/