Location returns null value sometimes - android

if (ActivityCompat.checkSelfPermission(super.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(super.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(super.getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
LogUtils.v(TAG, "Latitude : " + latitude);
LogUtils.v(TAG, "Longitude : " + longitude);
}
}
Sometimes I get the value, but then I do not know what happens that gives me null.

Android documentation says that Location can be null in these cases:
Location is turned off in the device settings. The result could be
null even if the last location was previously retrieved because
disabling location also clears the cache.
The device never recorded its location, which could be the case of
a new device or a device that has been restored to factory
settings.
Google Play services on the device has restarted, and there is no
active Fused Location Provider client that has requested location
after the services restarted. To avoid this situation you can create
a new client and request location updates yourself.

Related

Location-Manager not returning location consistently

I am using Network Provider to get the last known location of the user. When I tested it, It was working perfectly in one of my phones, but latitude and longitude is returning null on another phone. Is there an alternative to location manager to get a more consistent result. Or is there some other bug in my code
Here is my Permission checking Code:
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Please Grant Location Permissions")
.setPositiveButton("Ok", null)
.show()
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
101
)
}
And my location request code
longitude =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?.longitude
latitude =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?.latitude
val geocoder = Geocoder(this)
if (latitude != null && longitude != null) {
val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
val cityName = addresses[0].subAdminArea
}
As documentations says
Gets the last known location from the given provider, or null if there is no last known location. The returned location may be quite old in some circumstances, so the age of the location should always be checked.
This will never activate sensors to compute a new location, and will only ever return a cached location.
See also getCurrentLocation(String, CancellationSignal, Executor, Consumer) which will always attempt to return a current location, but will potentially use additional power in the course of the attempt as compared to this method.
Params:
provider – a provider listed by getAllProviders()
Returns:
the last known location for the given provider, or null if not available
Throws:
SecurityException – if no suitable permission is present
IllegalArgumentException – if provider is null or doesn't exist
so in case if last location return null you must request new on or custom handler

How can I retrieve the last location in android when GPS/Mobile Data /Wifi is off

is android stores last location, if so is it possible to get the last location when GPS/Mobile Data/Wifi is off.
The last known location of the device provides a handy base from which to start, ensuring that the app has a known location before starting the periodic location updates.
check this link .its very useful to us.
http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html
You could use locationmanager
LocationManager locationManager = (LocationManager) getSystemService(getApplicationContext().LOCATION_SERVICE);
// default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);//get bese location provider
if (provider != null && !provider.equals(""))
{
//check for permission
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
String Latitude = "" + location.getLatitude();
String Longitude = "" + location.getLongitude();
}
}
}
You need permission
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Android GPS location problems

I have a problem with setting current location with GPS.
It works like it should(notification about finding location, then set it properly) on Android 5.0.1(Xiaomi Redmi Note 3)
But for example on Android 6.0 (Sony Xperia Z5 Compact) it doesn't work at all. No notification, GPS position set never. On Xperia I even don't have button on the right of map which is showed by line in code(mMap.setMyLocationEnabled(true);)
On Android 4.4.2(Gigabyte GsMart Roma R2plus) also no notification comes up, but I can see button of current location on right on top of screen. But still doesn't work like it should.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
}
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
emailicek = user.getEmail();
emailicek = emailicek.replace(".", "");
mDatabase = FirebaseDatabase.getInstance().getReference();
if (latitude != 0) {
if (longitude != 0) {
mDatabase.child("userdata/" + email + "/latitude").setValue(latitude);
mDatabase.child("userdata/" + email + "/longitude").setValue(longitude);
}
}
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
if (latitude != 0) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
} else {
mMap.animateCamera(CameraUpdateFactory.zoomTo(1));
}
}
Did you make sure you requested the right permissions in the Manifest?
to get the last known location you'll need
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
for network based location, or:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
for GPS based location.
By the way there are a lot of good reasons why you should consider moving to Play Services to get your location, I strongly suggest you to read this:
Getting the Last Known Location - Android Developers

I am getting the latitude and longitude as 0,0 [duplicate]

I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
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.
return;
}
locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//
}
in onLocationChanged method you can use location.getLatitude & location.getLongitude

How to find out why GPS coordinates are missing in Android?

I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
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.
return;
}
locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//
}
in onLocationChanged method you can use location.getLatitude & location.getLongitude

Categories

Resources