[英]Image.network throw error even after defining errorBuilder in Flutter
[英]empty mLastKnownLocation even after defining @NonNull
我正在尝试从这段代码中获取设备位置
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);
}
}
});
通常可以正常工作,但有时会引发以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at SecondFragment$1.onComplete(SecondFragment.java:230)
代码的第230行是:
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(), //Line230
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
我什至不理解@NonNull屏蔽后,代码如何在这里出现并给出nullpoint异常。
此外,仅在仿真器中会出现此问题。 在真实设备中,我没有发现此错误(即应用程序没有像在模拟器中那样崩溃)
NonNull表示返回的值不为null。 这并不意味着函数的返回值(例如getResult())不能为null。
另外,无论如何包装,getLastKnownLocation始终可以返回null。 如果要确保获得位置,请使用getSingleUpdate并等待回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.