MuttaCeo
MuttaCeo

Reputation: 33

GeoPoint cant get my current Location and throws a java.lang.NullPointerException

AM trying to access the device location using Geopoint but unfortunately am getting an error thrown is double android.location.Location.getLatitude()' on a null object reference and have read alot of tutorials but am still facing this problem

Here is my code

private void getLastKnownLocation() {

        if ( ActivityCompat.checkSelfPermission (this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission (this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED ) {
            return;
        }

        mFusedLocationClient.getLastLocation ().addOnCompleteListener (new OnCompleteListener<Location> () {
            @Override
            public void onComplete(@NonNull Task<Location> task) {

                if ( task.isSuccessful () ) {
                    Location location = task.getResult ();
                    GeoPoint geoPoint = new GeoPoint (location.getLatitude (),location.getLongitude ());
                    Log.d (TAG, "onComplete: latitude"+ geoPoint.getLatitude ());
                    Log.d (TAG, "onComplete: latitude"+ geoPoint.getLongitude ());

                }

            }
        });

    }

The Error thrown

Upvotes: 0

Views: 42

Answers (1)

Prashant Jha
Prashant Jha

Reputation: 604

getLastLocation() can give you null value depending on availability. In this case you need to do call requestLocationUpdates and listen to any new location update.

Upvotes: 1

Related Questions