简体   繁体   中英

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:

      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.

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. It doesn't mean that the return of a function on it (like getResult()) can't be null.

In addition, getLastKnownLocation can always return null, no matter how you wrap it. If you want to assure that you get a location, use getSingleUpdate and wait for the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM