即使在定义@NonNull之后,也会清空mLastKnownLocation

时间:2018-03-09 07:22:57

标签: 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) {
        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异常。

此外,此问题仅在模拟器中发生。在真实的设备中,我没有发现这个错误(即应用程序没有像在模拟器中那样崩溃)

1 个答案:

答案 0 :(得分:2)

NonNull表示返回的值不为null。这并不意味着函数的返回(如getResult())不能为null。

此外,无论如何包装,getLastKnownLocation都可以返回null。如果您想确保获得位置,请使用getSingleUpdate并等待回调。