0

I was fetching the current Latitude and Longitude for my project, it was working perfectly at first, but now I'm retrieving null values. I do have turned on the Location and given permission for the location in the physical device but still getting the null value. My code is

mMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        double cLatitude = location.getLatitude();
        double cLongitude = location.getLongitude();
        LatLng currentLocation = new LatLng(cLatitude, cLongitude);
        System.out.println("Current Location : "+cLatitude+", "+cLongitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(cLatitude, cLongitude), 13f));

The error I'm getting is

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
Nensi Kasundra
  • 1,980
  • 6
  • 21
  • 34
Niroop Nife
  • 356
  • 1
  • 5
  • 18

2 Answers2

0

What is the problem ? You can have a null location if no location has been retrieved, because you are in a building for example.

Here is a more robust way to retrieve the location

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

Note that it is recommended to use the fused location provider : https://developer.android.com/training/location/retrieve-current

Bruno
  • 3,872
  • 4
  • 20
  • 37
0

Add LocationListener to get the current location.

private void getLocation() {
      // Get the location manager
      LocationManager locationManager = (LocationManager) 
          getSystemService(LOCATION_SERVICE);
      Criteria criteria = new Criteria();
      String bestProvider = locationManager.getBestProvider(criteria, false);
      Location location = locationManager.getLastKnownLocation(bestProvider);
      LocationListener loc_listener = new LocationListener() {

        public void onLocationChanged(Location l) {}

        public void onProviderEnabled(String p) {}

        public void onProviderDisabled(String p) {}

        public void onStatusChanged(String p, int status, Bundle extras) {}
      };
      locationManager
          .requestLocationUpdates(bestProvider, 0, 0, loc_listener);
      location = locationManager.getLastKnownLocation(bestProvider);
      try {
        lat = location.getLatitude();
        lon = location.getLongitude();
      } catch (NullPointerException e) {

      }
    }
Jinn
  • 72
  • 7