Every once in a while my app will crash when it attempts to get the user location. Unfortunetley I fo not have the error, because it has never happened when I am plugged into my computer...
I am using this to get my user location:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
I am thinking sometimes this might be null? If so how can I fix this force close?
Its not force closing while getting location.. its getting force closed while assigning longitude and latitude.. put an if(location!=null) before asigning the values
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//location might be null so
if(location != null)
{
double longitude = location.getLongitude();
double latitude = location.getLatitude();
}
You have no guarantee that location won't be null (there might not be a last known location), so you'll have a NullPointerException in
location.getLongitude()
Check that location != null before proceeding.
Always use Try & catch block when there's a chance of Exception.You will get NullPointerException if location returns null.
try {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
} catch (Exception e) {
}
I would recommend not rolling your own GPS.. Use Fused Location Provider:
Here is an example :
http://www.kpbird.com/2013/06/fused-location-provider-example.html?m=1
Related
I have a problem with getting current location because, I have in my MainActivity the listener:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
And I have a second activity where I would, when i click on button, calculate distance from my location and gps coordinate that I will pass with distanceTo and return true if the distance is beetween 0 and 200.
So I have a function in SecondActivity
private boolean checkCoordinate(String gps) {
LocationManager lm = (LocationManager) getSystemService(App.getContext().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return false;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
Location loc1 = new Location("");
loc1.setLatitude(currentLatitude);
loc1.setLongitude(currentLongitude);
String[] sep = gps.split(",");
double latitude = Double.parseDouble(sep[0]);
double longitude = Double.parseDouble(sep[1]);
Location loc2 = new Location("");
loc2.setLatitude(latitude);
loc2.setLongitude(longitude);
float distanceInMeters = loc1.distanceTo(loc2);
if(distanceInMeters < 200){
return true;
}else{
return false;
}
}
But the problem is that someTimes and maybe when I don't change my location the function:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return null, and I don't understand how know my current location because I have already set requestLocationUpdates.
so I how can know my current location?
getLastKnownLocation will return null if GPS based location is disabled in system or there was no GPS fix since system startup. If you want to ensure there is a location you can use the requestSingleUpdate-method, it will not return until there is a location available.
It might also be a good idea to not use the APIs based on specific provider name if it's not important to use a specific provider (usually it is not important how you got the location). The API contains methods that take a Criteria-object instead of a provider name and you can define very precisely what accuracy level etc. you want.
I have a simple location manager that normally works, however when the Android device has been turned off and then turned back on, the android location manager returns Null even when I have it requesting updates. I am aware that getLastKnownLocation can return null, however I believe I am handling that in my code. All suggestions Appreciated.
Apparently lon = location.getLongitude(); is crashing it.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
the android location manager returns Null even when I have it requesting updates
Correct. Requesting updates requests that Android start trying to find out where the device is. That will take a while. In the meantime, getLastKnownLocation() can very well return null.
getLastKnownLocation() is generally only useful if you would like to know the location, but if that data is not ready, you can move on without it. If you need the location, and getLastKnownLocation() returns null, you will to wait to use the Location until onLocationChanged() is called. Note that onLocationChanged() may never be called, as there is no requirement that the user have any location providers enabled, and there is no requirement that the device be in a position to actually get location fixes.
I saw your reply on the airplane mode but you do however have bad practices in your code.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
// request location update!!
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lon = location.getLongitude();
lat = location.getLatitude();
}
you already saw here that location in null, that means that you can't access the inner properties such as latitude and longitude. In any case, location requests are asynchronous and it takes a short amount of time for them to start.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Get last known location
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Update if not null
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
//Request update as location manager can return null otherwise
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
lat = location.getLatitude();
lon = location.getLongitude();
}
}
Even here, in the "else" clouse, you can't access the location right away. that means that you can't immediately get the location (it will just hold the last value).
What you should do is implement the onLocationChanges method and hadle the location there in asynchronous way. like this:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
else
{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
}
The only problem was that I had airplane mode enabled on the Android Phone. I'm a bit embarrassed now!
Hi I have implemented a location listener in my app which uses the Network Provider to get the GPS values. It's working fine, but now I want to get GPS using network provider and GPS provider. am trying but am getting the same value.
here my code
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Where i have to use networkLoc and gpsLoc?
#Override
public void onLocationChanged(Location location) {
double lat1 = (double) (location.getLatitude());//here i get the latitude value..how to know these values are from different provider
double lng1= (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
It may be the case, that if the user has GPS Enabled your line
provider = locationManager.getBestProvider(criteria, false);
is returning LocationManager.GPS_PROVIDER already, so you just query getLastKnownLocation(provider) twice with the same Provider. Try this instead:
Location networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
or if you really don't care which one to use
List<String> providers = locationManager.getProviders(false);
Location[] loc = new Location[providers.size];
int i = 0;
for (String provider: providers){
loc[i++] = locationManager.getLastKnownLocation(provider);
}
EDIT: due to refactoring of the question
//query provider from Location
public void onLocationChanged(Location loc){
String provider = loc.getProvider();
if (provider.equals(LocationManager.GPS_PROVIDER)){
//GPS Location
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)){
//Network Location
}
....
}
i am done code for getting current lat/long as follow but i always get null from lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); method.
i have tried by 2 ways.
the code is below.
first way,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
and second way,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Log.d("GPS_PROVIDER","GPS_PROVIDER = " + lm.isProviderEnabled(LocationManager.GPS_PROVIDER));
Log.d("NW_PROVIDER","NW_PROVIDER = " + lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListenerAdapter()
{
#Override
public void onLocationChanged(Location location)
{
if(location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
}
});
LocationListenerAdapter class is implements the method of LocationListener interface and i keep all method blank
i.e no code written into that methods.
i also use gpx and kml file for emulator to change lat/long but i didn't get yet.
can any one provide best answer.
Thanks in advance.
I have a problem in getting the user's location (my location). My code is
double lat;
double lng;
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(!locationManager.isProviderEnabled(provider)){
locationManager.setTestProviderEnabled(provider, true);
}
boolean enabled = locationManager.isProviderEnabled(provider);
if(enabled){
Toast.makeText(LoginActivity.this,"provider enabled",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"provider disabled",Toast.LENGTH_LONG).show();
}
if(location!=null){
lat = location.getLatitude();
lng = location.getLongitude();
AlertDialog.Builder ab=new AlertDialog.Builder(LoginActivity.this);
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>Location" +"</font></b><br>"
+location.toString()+"<br>Latitude: "+lat
+"<br>Longitude "+lng));
ab.setPositiveButton("ok",null );
Toast.makeText(LoginActivity.this,"You are at "+location.toString(),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(LoginActivity.this,"Location not found",Toast.LENGTH_LONG).show();
}
My problem is I am getting the location as null while the application message provider is enabled. I have not found any problem in this code. I have also tested it on a device, it shows the provider is enabled and the location isn't found.
I have not implemented the location listener in the class.
Is it necessary to implement location listener in my class?
You are only getting the last known location from the phone. If this is null, which it is if no last known location is available, you are not trying to receive locations in any other way.
You should implement a LocationListener an register it to receive location updates according to this guide: http://developer.android.com/guide/topics/location/obtaining-user-location.html This will cause the phone to try to get the users location and hand it over to your application in the form of a Location object.