[英]empty mLastKnownLocation even after defining @NonNull
I am trying to get the device location from this piece of code 我正在尝试从这段代码中获取设备位置
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);
}
}
});
which generally works fine, but sometimes it throws error as: 通常可以正常工作,但有时会引发以下错误:
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)
The line 230 of the code is: 代码的第230行是:
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(), //Line230
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
I don't understand even after taking @NonNull shield, how the code goes here and gives nullpoint exception. 我什至不理解@NonNull屏蔽后,代码如何在这里出现并给出nullpoint异常。
Also, this problem occurs only in emulator. 此外,仅在仿真器中会出现此问题。 In real device, I havn't found this error (ie the app is not crashing like it does in emulator)
在真实设备中,我没有发现此错误(即应用程序没有像在模拟器中那样崩溃)
NonNull means the value returned is not null. NonNull表示返回的值不为null。 It doesn't mean that the return of a function on it (like getResult()) can't be null.
这并不意味着函数的返回值(例如getResult())不能为null。
In addition, getLastKnownLocation can always return null, no matter how you wrap it. 另外,无论如何包装,getLastKnownLocation始终可以返回null。 If you want to assure that you get a location, use getSingleUpdate and wait for the callback.
如果要确保获得位置,请使用getSingleUpdate并等待回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.