issue getting last known location - android

I test my apps on two phones (1) an LG Optima running 2.3.7 and (2) a galaxy S3 running 4.1.2. The following code always works on the LG and always fails with a nullPointerException on the Galaxy..
try { //sometimes getting the last known location gets a nullpointerexception
String locationProvider = LocationManager.GPS_PROVIDER;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLoc = locMgr.getLastKnownLocation(locationProvider);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()));
map.animateCamera(center);
DebugLog.debugLog("Instantiated new Location listener. Moved camera to: " + myLoc.getLatitude() + myLoc.getLongitude() , false);
} catch (Exception e) {
DebugLog.debugLog("Exception getting lastknownlocation - doing without" + e, false);
}
Is there something wrong with this code?
Thanks,
Gary

Is there something wrong with this code?
You are not checking to see if myLoc is null. getLastKnownLocation() does not have to return a non-null value.

Related

Trying to get latitude and latitude with Network provider

I am trying to get my current coordinates with network provider and not gps provider.
I was able to figure out the solution for that but I am a bit confused with the concept in this scenario.
Working Code
Here's my code for getting my coordinates:
public void getLocation(){
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
if(appUtils.isOnline()){
try{
Geocoder geocoder = new Geocoder(
MainActivity.this.getApplicationContext(),
Locale.getDefault());
Location locationNetwork = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
List<Address> list;
if(locationNetwork!=null){
Toast.makeText(context,"Network Available!!",Toast.LENGTH_LONG).show();
list = geocoder.getFromLocation(locationNetwork.getLatitude(),locationNetwork.getLongitude(),3);
if(list!=null&&list.size()>0){
latitude = list.get(0).getLatitude();
longitude = list.get(0).getLongitude();
Toast.makeText(context,String.valueOf(latitude) + " (....) " + String.valueOf(longitude),Toast.LENGTH_LONG).show();
int count = 0;
while (latitude==null||longitude==null){
latitude = list.get(count).getLatitude();
longitude = list.get(count).getLongitude();
count++;
Toast.makeText(context,String.valueOf(latitude) + " --- " + String.valueOf(longitude),Toast.LENGTH_LONG).show();
}
}
}else{
Toast.makeText(context,"No response!!",Toast.LENGTH_LONG).show();
}
}catch (IOException e){
e.printStackTrace();
}
}else{
Toast.makeText(context,"Server not responding",Toast.LENGTH_LONG).show();
}
}
This piece of code is working perfectly fine when the gps is enabled. If gps is disabled, it doesn't work.
Now, if we are setting the location to NETWORK_PROVIDER:
Location locationNetwork = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Why do we still require gps ?
Now if I change it to PASSIVE PROVIDER:
Location locationNetwork = locationManager
.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
It works fine with the passive provider. Why is it that ?
Can someone explain what is the major difference here and what would be the right way to get the coordinates with network provider ?
I know this question is been asked several times and I did went through it. I just want to get cleared with this concept.
Thank's in advance.. :)
It doesn't require GPS to use the network provider, I've done it many times. However, getLastKnowLocation may not return a value if either it has never had an app request updates for that provider, or if the last time that happened was too long ago. You cannot count on that function always returning non-NULL. If you want to ensure that you get a location, use requestSingleUpdate instead. This will always get you a location (assuming the provider you use is enabled), but may take some time- a result may not be immediately available.
(There is one other time that function may never return- if you use the GPS provider and it can't get a lock on enough sattelites to find a location. Such as if you're in an underground parking garage).
This is the bit of code that I use to quickly get the current location, by checking all available network options.
private double[] getGPS(){
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}

distanceTo does not work while wifi is turned off

Hello this is a very bizzare error I am having. I am trying to get the distanceTo() from my location to a fixed location which I know how far it is. When my WiFi is turned off I get a very strange number but when the WiFi is on, even if it is not connected to any network I get the correct number. What would be the cause of this. I am testing on a Samsung Galaxy S3.
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
str = locationManager.getBestProvider(crit, false);
locationManager.requestLocationUpdates(str , 0, 1, this);
#Override
public void onLocationChanged(Location location) {
LatLng myLatLng = new LatLng(location.getLatitude(), location.getLongitude());
Location destination = new Location("dest");
destination.setLatitude(54.008447);
destination.setLongitude(-2.783383);
float distance = location.distanceTo(destination);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(myLatLng, 15);
mMap.animateCamera(cameraUpdate);
String destLocation;
destLocation = distance/2 +"";
Log.e("distance", destLocation);
locationManager.removeUpdates(this);
}
I don't use the getLastKnownLocation because I read somewhere that it is not reliable and it is better to get a location update before showing your location.
When you see the blue dot on the map, use mMap.getMyLocation() or mMap.setOnMyLocationChangeListener(...) instead of all the code that uses LocationManager. You will get the correct location.

Android GoogleMaps v1 LocationManager working odd on 4.4 kitkat

I have an application that used to locate a user's location with this code
public static Location getCurrentLocation(Context context) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
String provider = lm.getBestProvider(c, true);
Location location;
if (provider == null) {
location = new Location("gps");
location.setLatitude(U.LATITUDE);
location.setLongitude(U.LONGITUDE);
} else {
location = lm.getLastKnownLocation(provider);
if (location == null) {
location = new Location("gps");
location.setLatitude(U.LATITUDE);
location.setLongitude(U.LONGITUDE);
}
}
return location;
}
This code appears to only be returning the behavior when provider is null or location is null. My guess is that something changed in this code.
String provider = lm.getBestProvider(c, true);
I have some code very similar to yours and it stopped working on my device after the upgrade to Android 4.4 (i.e. getBestProvider returned null which it never did before).
I discovered the reason when I saw that another App displayed that the NetworkProvider wasn't available (although I had perfect connection to both wifi and 3G) and it could not get a GPS signal (obviously, because I was indoors). Then I toggled Android's location quick setting and a dialog popped up, asking me to agree to the new location management of Android 4.4 (see https://support.google.com/nexus/answer/3467281). Afterwards, my code worked as before.

Location mapping not returning on different devices

I have this code for getting the long and lat coordinates.
String bestProvider;
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, true);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
}else{
geocoder = new Geocoder(this);
try {
setLat((double)location.getLatitude());
setLng((double)location.getLongitude());
}catch (Exception e) {
e.printStackTrace();
}
}
I tried using different devices. Some returns a value for lat and long. Some do not. All devices were connected to the internet and gps enabled. Do you guys have any idea on what is causing this? Thanks!
It is due to getLastKnownLocation which may or may not exists. I suggest you to request single location update. Also remember that lastknownlocation is not necessarily accurate one it may belong to 2 days before.
dev guide:
http://developer.android.com/reference/android/location/LocationManager.html
A guide about single update
http://androidexperinz.wordpress.com/2012/04/19/current-location-update/
If there is no previous captured location, then getlastknown location does not return any value.So you need to implement the location listener to capture the location.

Android Runtime GPS Location - Blackberry Device - not working

My app has been ported from Android to blackberry and it works fine...
the only thing not working is the GPS location which works on the android....
the app displays a message to the using that we are trying to find the location and if no location is found we tell the user that we could not retrieve a location..
here is the code
private void gpsLocation()
{
//Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Provide Criteria
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 400, 1, this);
if(location != null){
onLocationChanged(location);
} else{
Log.i(TAG, "no GPS location available - waiting for GPS fix");
Toast.makeText(getApplicationContext(), R.string.gpsWaitingToast, Toast.LENGTH_SHORT).show();
if (Debug.GPS_USE_MONTREAL) {
currentLatitude = Double.valueOf(Debug.GPS_LAT_MONTREAL); currentLongitude = Double.valueOf(Debug.GPS_LNG_MONTREAL); // montreal
}
waitForGpsFix(GPSFIX_DELAY);
}
its not working,, I restarted the app ,, did it next to a window and all that stuff..
nothing works..
your advise and help is greatly appreciated.
Regards
There was previously a bug where LocationManager.NETWORK_PROVIDER returned null, which may still be returned by the locationManager.getBestProvider() method. This should be fixed in the newer OS builds, however.
If you'd like to fix your code immediately, all you would need to do would be to set:
provider = LocationManager.GPS_PROVIDER
as in the early stages, GPS_PROVIDER was the only provider that was implemented in the player.

Categories

Resources