Location manager give null location in android [duplicate] - android

This question already has answers here:
LocationManager's location in Android returns null
(2 answers)
Closed 8 years ago.
i am trying to get the current location in android for that i have used the android and following is my code
locationManager = (LocationManager) getSystemService(this.context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(true);
crta.setBearingRequired(true);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Log.d("","provider : "+provider);
provider = LocationManager.GPS_PROVIDER;
Log.d("","provider : "+provider);
locationManager.requestLocationUpdates(provider, 0, 0, (LocationListener) this);
Location location = locationManager.getLastKnownLocation(provider);
//isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (location != null)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();
txtLat.setText("Latitude"+latitude+"longitude"+longitude);
Log.d("not null", "location is not null");
}
else
{
Toast.makeText(getApplicationContext(), "locatyion is null", Toast.LENGTH_LONG).show();
Log.d("null","location is null");
}
The problem is that it doesnt gives me my current location when i open the application the location is null. Can anyone help ? i have seen many examples and tried others too but didnt work.
I have added
if (!isNetworkEnabled)
{
Toast.makeText(getApplicationContext(), "No network provider the gps wont work", Toast.LENGTH_LONG).show();
// no network provider is enabled
}
else{
Toast.makeText(getApplicationContext(), "Network is available", Toast.LENGTH_LONG).show();
}
and its says gps is available and network is not available

Code need to be async with a broadcast receiver of location changed listener...
That happens because GPS needs some time to provide a location, when it starts for the first time everything is null.
see the code below:
public class Example extends Activity implements LocationListener {
LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
// Do something with the recent location fix
// if it is less than two minutes old,
// otherwise wait for the update below
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
// You need to call this whenever you are done:
// mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
more here

Related

How to get the new latitude and longitude cordinates from android

How i am getting location details:
AppLocationService appLocationService = new AppLocationService(getApplicationContext());
Location nwLocation= appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
nwLocation.getLatitude();
nwLocation.getLongitude();
What is happening since my code has llast known location .... its giving me the last location that was updated say now its evening. its giving me the location updated during morning
What i want:: how can i make a fresh network request to get the current location at my position
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 0;
private static final long MIN_TIME_FOR_UPDATE = 0;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Your code is registering to receive location updates and also returns the last known location. What happens is expected because you didn't wait to receive an updated one.
Once the method "onLocationChanged" was called by the system you'll have the new one. You can then send a broadcast from the service.
You are trying to get the current location in a synchronous mode which is not possible as it takes some time to lookup the updated one.
The primary reason why you aren't getting updated location information quickly is that you're relying on the NETWORK_PROVIDER.
You should instead use this
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
How to call Explicitly onLocationChanged
public void locationlist()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
50, 0, this);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {}
if(location == null)
{
}
else{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
}
now call the method locationlist where you want like in a timer.
Use onLocationChanged method and get the longitude and latitude from the parametr location
Code:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = new Location(location);
latitude=mCurrentLocation .getLatitude();
longitude=mCurrentLocation .getLongitude();
}

Why doesn't onLocationChanged method get called in service?

I am getting my current location in the form of latitudes and longitudes. My problem is that once I get the coordinates it doesn't get updated when I move to another location.I think onLocationChanged method is not getting called. I read here http://www.lengrand.fr/2013/10/onlocationchanged-is-never-called-on-android/ that it doesn't get called by itself. I have gone through most of the tutorials and can't find a solution.So how can I call onLocationChanged method in my service. Please suggest me step by step.
My codes are as follow:
public class GPSTracker extends Service implements LocationListener {
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
}
#Override
public void onLocationChanged(Location location) {
getLocation();
}
Make sure you requestLocationUpdates(...) from the LocationManager (which in your case it seems you do)
If your inside a building and your device doesn't get GPS fix onLocationChanged(...) is not called, I had the same issue (when debugging in my home) but going outside I saw that the function is called once GPS fix is retrieved.
try
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(getApplicationContext(), "My Position !!!"+ location.getLatitude + location.getLongitude,
Toast.LENGTH_LONG).show();
}
It is weird that you are even getting a single location update. From you code it looks like you call getLocation() when you recieve a location change, but you then only setup your location requests inside of the getLocation() function (i.e. you should never enter the getLocation() function). This is how I implemented a location listener for gps data:
Note: I used this in a service, but I did not have my service implement LocationListener.
private void setupLocationUpdates() {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
mLocationListener = new LocationListener() {
// Called when the location has changed.
public void onLocationChanged(Location location) {
mLocation = location;
}
}
// Called when the provider is disabled by the user.
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "Status Changed: " + String.valueOf(status) + " Provider:" + provider);
}
// Called when the provider is enabled by the user.
public void onProviderEnabled(String provider) {
if(provider.equalsIgnoreCase("gps")) setNotification(Constants.GPS_ENABLED);
Log.d(TAG, "Provider: " + provider + " ENABLED");
}
// Called when the provider status changes.
public void onProviderDisabled(String provider) {
if(provider.equalsIgnoreCase("gps")) setNotification(Constants.GPS_DISABLED);
Log.d(TAG, "Provider: " + provider + " DISABLED");
}
};
mlocationProvider = LocationManager.GPS_PROVIDER;
// Register for location updates
mLocationManager.requestLocationUpdates(mlocationProvider, 0, 0, mLocationListener);
// Add a GPS Listener to notify when searching for signal and when fix is acquired
mGpsListener = new GpsListener();
mLocationManager.addGpsStatusListener(mGpsListener);
}

device location is always null

I have gone through many posts on SO regarding this issue:
Tried everything in Here,
Here and Here Nothing works. Everytime location is null. On device and on emulator :(. My GPS is on,internet is on and my manifest has following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I use following code to get the location i.e the longitude and latitude of the device...however in every case I get location as null
public void find_Location() {
Log.d("Find Location", "in find_location");
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(location_context);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 1000, 0,
new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
}
});
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
Toast.makeText(LbsGeocodingActivity.this, "Location Not found",
Toast.LENGTH_LONG).show();
} else {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(LbsGeocodingActivity.this,
"LAT..." + latitude + "\nLONG..." + longitude,
Toast.LENGTH_LONG).show();
// addr=ConvertPointToLocation(latitude,longitude);
// String temp_c=SendToUrl(addr);
}
}
}
It takes some time before the position is determined, and it can change over time. It's probably just not available yet when you check it.
When a position fix becomes available, you will be notified in onLocationChanged.
How could I be so stupid..My bad....In settings Use Wireless networks was not selected!....That cause all the problems !!
Now I am able to get a location.
It took me 16 hrs to get to this...my productivity going down for sure! :(

Unable to get latitude and longitude from android

getLastKnownLocation always return null value. I have enabled geo fix and gps on emulator. However, there is no gps signal on the notification bar when running this on emulator. May I know is there any mistake in my code? Thanks.
public void onCreate(Bundle savedInstanceState) {
LocationManager location = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.near_layout);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String bestProvider = location.getBestProvider(criteria, true);
LocationListener ll = new mylocationlistener();
Location loc = location.getLastKnownLocation(bestProvider);
if(loc != null)
{
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(nearPlace.this, " nice" + latitude, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(nearPlace.this, "Location not available. GPS is not enabled.", Toast.LENGTH_LONG).show();
}
location.requestLocationUpdates(bestProvider, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(nearPlace.this, " nice" + location.getLatitude(), Toast.LENGTH_LONG).show();
nearPlaceDownloaderTask getNearPlace = new nearPlaceDownloaderTask();
getNearPlace.execute(ANDROID_WEB_LINK + "gt.php?la=" + location.getLatitude() + "&lo=" + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The reason your code is not working, is because you have specified the following criteria:
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
Android will prefer to use network location over GPS, because you don't care about the accuracy. By specifying an accuracy of 20 meters or so, it will probably automatically invoke GPS.
To manually invoke GPS location updates, override bestProvider:
bestProvider = LocationManager.GPS_PROVIDER;
You can really simplify this into two lines of code:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval,
precision, listener);
Don't forget to unregister your listener:
locationManager.removeUpdates(listener);
You might also want to check this out geofix not working
Also make sure you have mock locations allowed set in the emulator. Take a look at Pauls answer as well, which is why I was asking in comments what provider was returned

LocationManager will not return destination

I created this earlier on today, but it is not working. Location manager returns null, and I've even implemented the listener. Any ideas to the problems. thanks.
Edited:
I think this line is the problem
Location location = locationManager.getLastKnownLocation(provider);
Basically, if location is null, it will go into the else part of the if statement below it. Every time I compile the code, it will go into the else statement meaning it location is not updating.
public class Activity1 extends Activity implements LocationListener {
/** Called when the activity is first created. */
JoshTwoActivity main;
Activity2 two;
boolean checkTick = false;
String locationplace = "";
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
System.out.println(locationManager.isProviderEnabled(provider));
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
getLastKnownLocation() returns a location with the last known location fix for a provider. If the provider returns null, the provider has never had a location fix. It doesn't mean the provider is not available.
Once you call getLastKnownLocation() you should check to see if the results are accurate or recent enough for your purpose. If not you should request location updates using requestLocationUpdates().
This blog post contains everything you need to know about writing code using location providers.
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Ok my first guess is that you are not giving location fix via command line or by using eclipse DDMS perpective. If this is problem go open DDMS perpecive and give latitude and longtiude you want and send it. So location will not be null from now on if this is the problem.
The following link may help you in understanding how to use emulator in finding the location. The last section of this page has that information.
http://developer.android.com/guide/topics/location/obtaining-user-location.html

Categories

Resources