Android 即使在定义@NonNull之后,mLastKnownLocation也为空
我正试图从这段代码中获取设备位置Android 即使在定义@NonNull之后,mLastKnownLocation也为空,android,nullpointerexception,Android,Nullpointerexception,我正试图从这段代码中获取设备位置 private void getDeviceLocation() { /* * Get the best and most recent location of the device, which may be null in rare * cases when a location is not available. */ try { if (mLocationPermissionGranted) {
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
mMap.clear();
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
代码的第230行是:
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(), //Line230
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
即使在使用@NonNull-shield之后,我也不明白代码是如何运行的,并给出了null点异常
此外,此问题仅在emulator中发生。在真实设备中,我没有发现此错误(即应用程序没有像emulator中那样崩溃)非空表示返回的值不是空的。这并不意味着其上的函数(如getResult())的返回值不能为null
此外,getLastKnownLocation始终可以返回null,无论您如何包装它。如果您想确保获得位置,请使用getSingleUpdate并等待回调。您好,谢谢您的回复。请你扩大你的答案好吗?我是一个java程序员新手,不知道如何使用getSingleUpdate。谢谢
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(), //Line230
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));