task.getResult() return null?

Viewed 1437

After switching on location in settings task.getResult() returns null. If try it once more everything will be ok. What is the problem ? here is code

mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
    try {
        if (mLocationPermissionsGranted) {
            Task<Location> location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "onComplete: found location!");
                        currentLocation = task.getResult(); // task.getResult() returns null
                        if (currentLocation != null) {
                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location", cameraMovingMode);
                        }
                    } else {
                        Log.d(TAG, "onComplete: current location is null");
                        Toast.makeText(MainActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    } catch (SecurityException e) {
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
    }
2 Answers

A bit late to the party but I hope this serves for future references.

The main issue here is that if the user has or had the phone Location switched off, then all the last locations are wiped out by the phone system, therefore the task.getResult() of the onComplete listener being null. In this case, use instead of the onComplete listener, the onSuccess listener and if the location is null then use getCurrentLocation() to get the user's last location.

sorry but i forget how solved it. I found this code, hop it will help you

   try {
        if (mLocationPermissionsGranted) {
            mFusedLocationProviderClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                currentLocation = location;
                                isLocationEnabled = true;
                                moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), "My Location");
                            }
                        }
                    });
        }
    } catch (SecurityException e) {
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
    }
Related