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