Last time I put the code on oncreate method which can successfully capture the device longitude and latitude but currently I run again and it show nothing please anyone can advice me on this question?
original should be can found in last month but currently cannot found!
The code is like this.
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000 , 0, (LocationListener) this);
//get Location
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
la = String.valueOf(location.getLatitude());
searchla.setText("Latitude: "+ la);
lo = String.valueOf(location.getLongitude());
searchlo.setText("Longitude: "+lo);
so did i miss out something?
If it was me, I would test to see if the longitude and latitude are returning values. Try putting break points and see.
If they are, it's problem for conversion and if not, it's problem with retrieval. Not the answer but gives the problem a direction to look into.
If there is no other code places that affects visibility of textviews, the only part is permission scope. So the device has no permission and then it goes to out of scope.
Maybe it seems a dummy answer but can you check if the location service (GPS) is activated on the emulator?
On the second screen shot I do not see the Location On icon.
If this is not the case:
Since last time you (when it worked) have you switched the API version? It is the same emulator/settings?
EDIT: Marshmallow emulator problem - https://issuetracker.google.com/issues/37069061
Solution: update to a newer API version
Related
Im trying to getLastLocation(), but sometimes it is null. When that happens, I go to google maps just for a second, and return to my app and in 99% that will do. There is also one app that just returns city that you're in and it works even if my app can't getLastLocation(). I've noticed that when I use that other app, or google maps, or weather app, for a short time location icon will appear in status bar, but when I use my app that icon never appears, so I'm guessing that may be the problem?
What I need to do to assure that I get my location to be != null?
One more thing, sometimes I get my location (lat and long), but reverse geocoding goes to catch because List is empty? How to make sure it always is not empty?
The code that I use is just a copy/past from android developers.
If you are using Android Emulator it is expected that the location doesn't get updated unless you open the Maps App.
To ensure you get non-null location you need to request for location updates
You can do something like this
#SuppressLint("MissingPermission")
private fun getLastKnownLocation() {
// get last known location from fusedLocationProviderClient returned as a task
fusedLocationProviderClient.lastLocation
.addOnSuccessListener { lastLoc ->
if (lastLoc != null) {
// initialize lastKnownLocation from fusedLocationProviderClient
lastKnownLocation = lastLoc
} else {
// prompt user to turn on location
showLocationSettingDialog()
// when user turns on location trigger updates to get a location
fusedLocationProviderClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.getMainLooper()
)
}
// in case of error Toast the error in a short Toast message
}
.addOnFailureListener {
Toast.makeText(requireActivity(), "${it.message}", Toast.LENGTH_SHORT).show()
}
}
This is just a stub, you will need to handle permissions, create FusedLocationProviderClient, LocationRequest and LocationCallbackObject.
You may also need to prompt the user to Turn on Location Settings.
Please show us your GeoCoding code to elaborate further.
I simply need to get the user location. Preferably the exactly location, but if it's not possible, a rough location would be fine.
According to the docs:
LocationClient.getLastLocation()
Returns the best most recent location currently available.
and
LocationManager.getLastKnownLocation(String)
Returns a Location indicating the data from the last known location fix obtained from the given provider.
If my understanding is right, the former will give me a very good result (or null sometimes) while the latter will give me a result which would rarely be null.
This is my code (simplified)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationClient = new LocationClient(this, this, this);
#Override
public void onConnected(Bundle dataBundle) {
setUserLocation();
}
private void setUserLocation() {
myLocation = locationClient.getLastLocation();
if (myLocation == null) {
myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
if (myLocation == null) {
//I give up, just set the map somewhere and warn the user.
myLocation = new Location("");
myLocation.setLatitude(-22.624152);
myLocation.setLongitude(-44.385624);
Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
}
} else {
isMyLocationOK = true;
}
}
It seems to be working but my questions are:
Is my understanding of getLastLocation and getLastKnownLocation correct?
Is this a good approach?
Can I get in trouble using both in the same activity?
Thanks
LocationClient.getLastLocation() only returns null if a location fix is impossible to determine. getLastLocation() is no worse than getLastKnownLocation(), and is usually much better. I don't think it's worth "falling back" to getLastKnownLocation() as you do.
You can't get into trouble using both, but it's overkill.
Of course, you have to remember that LocationClient is part of Google Play Services, so it's only available on devices whose platform includes Google Play Store. Some devices may be using a non-standard version of Android, and you won't have access to LocationClient.
The documentation for Google Play Services discusses this in more detail.
I have the following code in my Service:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
Location location = locationManager.getLastKnownLocation(provider);
while(true)
{
if(...)//every 5 seconds it gets into
{
....//control if the location is not null
lat = location.getLatitude();
lon = location.getLongitude();
alt = location.getAltitude();
Log.i(TAG, "Latitude: "+lat+"\nLongitude: "+lon+"\nAltitude: "+alt);
}
else {
Log.i(TAG, "Error!");
}
}
This code kind of works in my emulator (GPS are inserted into the Log), but in my Mobile device, this code gets to the else branch. Could somebody tell me where is the problem? In my code or in my Mobile device? Thanks in advance.
P.S.: The GPS is turned on, in another apps it works.
getLastKnownLocation() will not fetch subsequent location from the GPS provider. It will return (as the name may suggest) the last known location requested by some code. I assume that you check location being not null in the condition, which is not shown in your code. The location is null if the device "decided" that the last known location is too old or unreliable by other means. You need to request location updates and provide a location listener to get locations repeatetly.
There are lots of tutorials available. Here ist one. of them.
I know this has been asked a ton, so my apologies. I have the following code, and cannot get the location, always a null response. I am trying to avoid a LocationListener in this instance because I am already using an update Service, and the location really doesn't have to be that fine, so the last known location is good enough. Thanks for the help.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String providers[] = {"gps", "network", "passive"};
Location loc = null;
for(String x : providers) {
loc = lm.getLastKnownLocation(x);
if(loc != null) break;
}
if(loc != null) {
// do something, never reached
}
I have the following code, and cannot get the location, always a null response.
Of course.
I am trying to avoid a LocationListener in this instance because I am already using an update Service
I have no idea what this means, but I suspect that you will need a LocationListener whether you like it or not.
Android is not constantly checking your location. Particularly with GPS, that would be horrible for the battery. Android only checks your location when somebody is using requestLocationUpdates() or addProximityAlert().
I'm not sure but maybe this happens because you use an emulator?
I remember I've tried to check last known location and have something like yours error.
So I always check getLastKnownLocation(provider) != null before use it.
I have this bit of code;
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
gpslocation = Double.toString(lm.getLastKnownLocation("gps").getLatitude()) +" "
+ Double.toString(lm.getLastKnownLocation("gps").getLongitude());
Which works fine on both the emulator and my hero running android 1.5, but it Force Closes on the emulator of 1.6 and also on my tattoo.
What changed from 1.5 to 1.6?
OK, using this instead;
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Double latPoint = null;
Double lngPoint = null;
Location loc = lm.getLastKnownLocation("gps");
if(loc != null) {
latPoint = lm.getLastKnownLocation("gps").getLatitude();
lngPoint = lm.getLastKnownLocation("gps").getLongitude();
} else {
}
Toast.makeText(getBaseContext(),"test lat " + latPoint, Toast.LENGTH_LONG).show();
I get null toast, and null toast if i fire a location at the emulator before running the app.
In general, use adb logcat, DDMS, or the DDMS perspective in Eclipse to look at the Java stack trace associated with the "force close" dialog, to see what the problem is.
In your case specifically, it will not work because you have not turned on GPS in the code snippet.
You cannot reliably call getLastKnownLocation() on a provider unless that provider has been up and running. In your case, GPS is probably not running, and getLastKnownLocation() will return null.
You will need to register for location updates or proximity alerts, to get the GPS radio powered on and seeking fixes, before getLastKnownLocation() will work. Also, with the emulator, you will need to submit a fix (e.g., via DDMS) after registering for location updates or something before getLastKnownLocation() will return a non-null value.