我有一种方法可以在地图上显示设备的当前位置。我正在使用FusedLocationProviderClient
,因为它似乎是最准确的。
我currentLocation.getLatitude()
收到警告:
方法调用可能产生 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() );
}
}