簡體   English   中英

甚至在定義@NonNull之后仍為空的mLastKnownLocation

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM