getLastKnownLocations always returns null - android

I am unable to getLastKnownLocations on my Android device (Samsung Galaxy Note N7000) as it is always null, towers is detected as network so it is fine, anybody got any idea how to get my location?
d = getResources().getDrawable(R.drawable.songs_gray);
//Placing pinpoint at location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Toast.makeText(LocationActivity.this, "Towers: " + towers, Toast.LENGTH_SHORT).show();
Location location = lm.getLastKnownLocation(towers);
Toast.makeText(LocationActivity.this, "Location: " + location, Toast.LENGTH_SHORT).show();
if(location !=null){
lat = (int) (location.getLatitude()*1E6);
longi = (int) (location.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, LocationActivity.this);
custom.insertPinPoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(LocationActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

With getLastKnownLocation() you can only get a Location object when the specified location provider is active.
The documentation says:
Returns a Location indicating the data from the last known location
fix obtained from the given provider. This can be done without
starting the provider. Note that this location could be out-of-date,
for example if the device was turned off and moved to another
location.
If the provider is currently disabled, null is returned.
To detect the current position and not the last detected one you need to enable the location provider(s). This tutorial should help you to understand how to work with location providers as GPS and network.

the last known location is only available if the location has been determined by another app prior to your call. start maps or some other app and let it get a location lock. then run your app.
if you really need location in your app, you need to fall back to some other method, because you cannot depend on there being a last known location.
as a side note, ACCESS_MOCK_LOCATION isn't required here. from the docs,
Allows an application to create mock location providers for testing

Nevermind found out my problem! Just needed to on Google's Location Services on my phone

Related

Android Emulator: Illegal Argument Exception Null at Location Provider

The application will run correctly on my real device just fine but as running on the
emulator, it immediately crashes and I receive an error message noting that the GPS coordinates are null. Even after opening DDMS, running the application, then sending coordinates and attempting the login, where the onCreate method will be called looking for GPS, it still notes null error (below)
All emulators I have created allow for GPS but still the error persists. The code for onCreate where GPS is first required is below:
// Ensuring a location, loop till find it
do {
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Just test displaying
lat = (float) (location.getLatitude());
lng = (float) (location.getLongitude());
} while (lat == 0.0);
The specific error message is:
java.lang.IllegalArgumentException: invalid provider: null at android.location.LocationManager.checkProvider(LocationManager.java:1623)
On android emulator you get null provider from locationManager.getBestProvider(criteria, false);
check this post: https://stackoverflow.com/a/20661039/4387543

Android using LocationManager Get Provider is "Passive" in My Moto G Android Phone

I need a little help with some information about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in My Device Motorola G I get provider="Passive" and also Location return Null My Motorola G is running on Latest Android Kit Kat(4.4) Android Os.
I also try this code in Other Devices so Provider is either Network Or GPS also find Location properly.
locationManager = (LocationManager) getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 1000, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getSherlockActivity(), "Location not available", Toast.LENGTH_SHORT).show();
}
I know that this is somehow an old question. But hope my answer will help others as well.
The issue is not related to the used device, actually the issue is how we use the provided API.
In the following code snippet, you pass true for the enabledOnly flag while you just need to pass it as false and it will work correctly at this time.
Instead of :
provider = locationManager.getBestProvider(criteria, true);
To be:
provider = locationManager.getBestProvider(criteria, false);
To clear this point:
If we set this flag "enabledOnly flag" to true, this means to return the requested best provider based on our criteria from the enabled only providers which will return the Passive provider.
While, if we set it to false, this will mean to return the requested best provider based on our criteria even if it is not enabled, which will return gps.
Btw, I am using Moto G too -but it's 2nd Gen- , and it worked with me this way :)
Hope this helps :)
READ THIS IF YOUR APP SUPPORTS kITKAT(4.4) VERSION OF ANDROID
I was having the same issue and my code was working perfectly in other devices not running kitkat,after a little bit of snooping around i found out that you have to explicitly turn on GPS to get location through wifi/gps. you can read about it here.
https://support.google.com/nexus/answer/3467281

GPS doesn´t work in IntentService

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.

get current location from Latitude and Longitude using gps

I got the Latitude and longitude values in Emulator using Telnet.(i.e) GPS.
I have a doubt (i.e) without google map can we able to get the current location using the latitude and longitude.
You can fetch the current location using GPS and Google map both. If you want to fetch location through Google map then plz show this tutorial. And you can see this previous asked question.
If you want to fetch location without Google map then you can be use location manager.
To do this, we need to add the fallowing code in the OnCreate method:
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
In the custom class MyLocationListener using implements the interface LocationListener.
We will add our own personal Location listener, so we can override some of the functions to do what we want. In our case we will just print a message to the screen in the fallowing cases:
onLocationChanged ( Location Update )
onProviderDisabled ( GPS Off )
onProviderEnabled (GPS On )
And add another mandatory method, which will do nothing.
onStatusChanged (We are not adding nothing here).
After that give the permission in AndroidManifest.xml file:
android:name="android.permission.ACCESS_FINE_LOCATION"
You can get latitude and longitude by this code
GPS_Location mGPS = new GPS_Location(MyApplication.getAppContext());
if (mGPS.canGetLocation) {
mLat = mGPS.getLatitude();
mLong = mGPS.getLongitude();
} else {
System.out.println("cannot find");
}
you must add the gps permissions and other permissions to your app

why does this work on android 1.5 but not 1.6 (location manager)

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.

Categories

Resources