I am new to the development of applications for Android and I am creating an application which makes use of the user's location. The problem is that sometimes I get a Lat and Long of (0,0). I mean, he can not read it. But this only happens with certain devices, which do not follow any pattern in common.
I really do not know the problem and I think it may be because the system can not get these coordinates when the application asks for them.
The code I use to get the user's location is the following:
private Location getMyLocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#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 ActivityCompat#requestPermissions for more details.
}
myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try
{
//El if es para que nos deje de mostrar el "checkpermission", y nos deje obtener la localizacion
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (myLocation == null)
{
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
}
else
{
if (myLocation == null)
{
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return myLocation;
}
The error that marks me is the following:
"Attempt to invoke virtual method 'double android.location.Location.getLatitude ()' on a null object reference"