How to find last location using android - android

I'm using the following code to get my last know location, but it is not working
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteia();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);

Hard to say given the lack of error information. Just a guess ... do you have these in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Related

Why my GPS does not give me the exact location?

I'm trying to get the exact longitude and latitude of a android device. The problem is that when setting data in google maps, I realize that the position is not correct. I think the device is getting any previously saved position
LocationManager locationManager;
String svcName = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(svcName);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("lon", longitude+"" );
Log.i("lat", latitude+"");
}else{
Log.i("Null", "Es nulo");
}
LocationListener
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider,int status,Bundle extras){}
};
xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
How can I fix it?? I need the current position of teh devices
The line:
Location location = locationManager.getLastKnownLocation(provider);
delivers the last know, even if that location is from yesterday.
Remove the line, cnage the code appropriate, and wait till you get an location event in onLocationChanged().
Further you may check: the timestamp of the location: caluclate the difference to current time and you know if it is a recent location.
Further check location getHoricontalAccuracy() (or named similar) if it is above 40m ignore the location.

Location is null on device

I am testing my app on a real device and getting a null location when the GPS is on. When I test on the emulator with dummy coordinates it works fine. What is wrong?
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
listener = new MyLocationListener();
viaGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
viaNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!viaGps && !viaNetwork) {
tracking = false;
} else {
if (viaGps) {
Log.d("", "gps is on");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if (viaNetwork) {
Log.d("", "network is on");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location == null) {
Log.d("", "location not fouond");
}
Try using this , it solved my problem
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Also check your permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
You need a Location listener:
Follow the documentation
Update:
You can also try that easy way: What is the simplest and most robust way to get the user's current location in Android?

android - GPS not accurate

i am trying to show on the map where i am.
I am in Israel and it shows me i am in Egypt.
I tried implementing all of the suggestions of different posts and non helped me solve my problem.
I turned on GPS.
I am connected to the Internet.
When i launch MAPS default android App it shows my real location!
MANIFEST PERMISSIONS:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
I also use the uses-library android:name="com.google.android.maps".
This is the relevant code from the MapActivity which extends LocationListener:
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
if(came_from.matches("FollowLocation"))
{
Location location;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String providerName = lm.getBestProvider(criteria, true);
// If no suitable provider is found, null is returned.
if (providerName == null)
{
// reflecting changes if distance travel by
// user is greater than 20m from current location
// and every 1 minute
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else
{
// reflecting changes if distance travel by
// user is greater than 20m from current location
// and every 1 minute
lm.requestLocationUpdates(providerName, 1*60*1000, 20, this);
location=lm.getLastKnownLocation(providerName);
}
gMapView = (MapView) findViewById(R.id.myGMap);
gMapView.setStreetView(true);
mc = gMapView.getController();
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
mc.setZoom(14);
}
else //in case we didn't get the location yet
{
lat = 32.08;
lng = 35.84;
mc.setZoom(9);
}
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
// Adding zoom controls to Map
gMapView.setBuiltInZoomControls(true);
// Add a location mark
MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
List<Overlay> list = gMapView.getOverlays();
list.add(myLocationOverlay);
}
}
/* This method is called when use position will get changed */
public void onLocationChanged(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// required for interface, not used
}
protected boolean isRouteDisplayed() {
return false;
}
These coordinates: lat = 32.08 lng = 35.84 are some spot in israel...
So..... What am i doing wrong ? Or what am i doing not right ? :P
Thanks!
I'd say that getLastKnownLocation is giving you that erroneous position for some reason. Your default of 32.08, 35.84 won't ever get reached because location will never be null. I'd suggest using the debugger to see which of your calls to getLastKnownLocation is getting hit, and what the value returned is.
I took my code and compared it to a working code from an example in the internet.
Not sure what solved the problem, but i definetly know that you should requestLocationUpdates after you finish to configure everything else.
Other people who encounter this problem - try taking a working code from the internet and comparing it step by step until it works on your app.

java.lang.NullPointerException about gps api?

as the title i have a question about the gps api
follow is my code
LocationManager loctionManager;
String contextService=Context.LOCATION_SERVICE;
loctionManager=(LocationManager) getSystemService(contextService);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = loctionManager.getBestProvider(criteria, true);
Location location = loctionManager.getLastKnownLocation(provider);
double a=location.getLatitude();
double b=location.getLongitude();
Log.d(""+a,""+b);
then the error is java.lang.NullPointerException
anyone can help me?thx
getLastKnownLocation() can return null you need to ensure it does not.
In order to get a Location you need at first to set permission in your Manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then in your code you need to listen for location avalability. You do that by registering a LocationListener. The activity will display, and when Android will have a location for you it will call you back.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
//Do what you want with your coordinates
}
loctionManager.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener);
If you are using the emulator and not a real device you need to force a location, you can use DDMS inside Eclipse to send a fake location:

Getting null from 'getLastKnownLocation' on SDK

I have a problem related to the Location API.
I tried the following code:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
loc is always null, when getLastKnownLocation() is called.
What is wrong?
Along with the permissions in your AndroidManifest.xml file, have you registered a location listener?
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener);
Then have a method, in this case locationListener, to complete your task
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
If you're running the code in the emulator, any calls to get the GPS location will return null until you explicitly update the location (via Eclipse or ADB).
I had the same problem as you, I always receive a null Location object, But finally it was solved in an easy way. You must have a valid GPS location, so, if the GPS is not enabled and you dont't have enough signal, the Location object will be ALWAYS null.
Have you set the permissions in your AndroidManifest.xml? You need these permissions in order to access the user's location with an application:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
Here's something you can use:
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Location loc = lm.getLastKnownLocation(bestProvider);
last_lat = loc.getLatitude();
last_lng = loc.getLongitude();
You need the instance Of LocationManager like this:
First Instance:
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Wrong:
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
Correct:
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

Categories

Resources