device location is always null - android

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! :(

Related

Get Location without using GPS and without Google Services via official API

I wonder if it's possible to get a location without Google Services and without using GPS (and thus using NETWORK_PROVIDER) on an Android device. My current code looks like this:
public void onButtonTap(View view) {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// we're done here
printLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) { }
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { }
};
String provider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
try {
location = locationManager.getLastKnownLocation(provider);
} catch (SecurityException se) {
}
if(location != null) {
// we're done here
printLocation(location);
}
if(location == null) {
try {
locationManager.requestSingleUpdate(provider, locationListener, null);
} catch (SecurityException se) {
}
} // end of onButtonTab (formatting issues)
private void printLocation(Location location) {
String latitude = String.format(Locale.US, "%.4f", location.getLatitude());
String longitude = String.format(Locale.US, "%.4f", location.getLongitude());
String slocation = "lat: " + latitude + ", lon: " + longitude;
Toast.makeText(getApplicationContext(), slocation, Toast.LENGTH_LONG).show();
}
So I basically query for the last location and if there's none I request an update. This works for PASSIVE_PROVIDER (if there's GPS activity) and of course for GPS_PROVIDER but I don't get a location with NETWORK_PROVIDER. The listeners method onLocationChanged never gets called. The app has the right permissions and locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is true.
Is this functionality just not working because there's no database (owned by Google and provided by Google Services) to compare against? Or does AOSP build it's own database over time (learning from GPS Data)? I doubt the later.
Little extra question: I can't use Fused Location Provider API as I don't have Google Services installed, can I?

How do i get my current location without GPS?

I want to get my current latitude and longitude using Mobile network provider, not GPS. AKA it should work without GPS with just your sim card. i have found many tutorials online claiming they find location with gps or network. however, they all seem to use GPS only! here or here and also here i don't want last knows location, as i don't wish to use GPS
Try This Code you can get current location without opening GPS
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
Do it via Location Manager.
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

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

Get last location latitude and longitude

This is my code.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Location location = getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LastLocationLat = location.getLatitude();
LastLocationLongi = location.getLongitude();
LocationLat = loc.getLatitude();
LocationLongi = loc.getLongitude();
if(loc.hasSpeed()) {
float mySpeed = loc.getSpeed();
Toast.makeText(getApplicationContext(), ""+mySpeed, 2000).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getApplicationContext(), "Gps onStatusChanged", Toast.LENGTH_SHORT).show();
}
}
But i did not get last location in this code i got same latitude and longitude
You are using LocationManager.NETWORK_PROVIDER to get locations. Your code implies you want GPS ("Gps Disabled")? In this case you should use LocationManager.GPS_PROVIDER.
LocationManager.NETWORK_PROVIDER is not very accurate (few hundred meters if locking to cell towers), so you might not detect the location change if you move less then 100m.
On the other hand, GPS is usually unavailable indoors or between tall buildings. Also GPS uses power so should not be used all the time (when app is in the background).
Read about Obtaining User Location, for the best approach to getting location with regards to accuracy vs service availability.
Hope this can help:
http://www.tutorials-android.com/learn/How_to_get_the_last_known_GPS_location.rhtml

Categories

Resources