My code putput always goes in else part. IT means {location} is null.
Any suggestions?
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);
location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();
} else {
//
}
.....
.....
....
If locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) returns null then it means you have never been located.
If you want to get the new location, you should make you activity extend the LocationListener interface and implement the following.
public void onLocationChanged(Location location) {
// Code to execute after being located
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
Don't forget to remove the location updates afterwards.
Related
I'm trying to use Lat & Lon values for a function I created, but I can't find a way how to get this values from the class "Locationer" to the MainActivity.
I have created a new method called getLat(), but I need a location variable in order to get the latitude value with this method.
I have no idea how to get this "location" and where it comes from in the class.
I've am testing it on my own device.
The Locationer class:
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class Locationer extends Activity implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();
//I make a log to see the results
Log.e("MY CURRENT LOCATION", myLocation);
}
public double getLat(Location location)
{
return location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
the code in my MainAcitivity.java:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Locationer locationListener = new Locationer();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
lat = **NEED YOUR HELP TO GET THIS VALUE**
lon = **NEED YOUR HELP TO GET THIS VALUE**
queryBooks(lat, lon);
You will have no latitude or longitude directly after setting the LocationManager. The onLocationChanged() will be called when it find a location. See here.
You can do the queryBooks(lat, lon); in the onLocationChanged().
Or you can use getLastKnownLocation(LocationManager.GPS_PROVIDER); but it will be less accurate and can provide you an old location.
Here what you can do in you MainActivity :
private LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
queryBooks(location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume() {
super.onResume();
//every second
int minTime = 1000;
//minDistance between two update
int minDistance = 10;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, mLocationListener);
};
#Override
protected void onPause() {
mLocationManager.removeUpdates(mLocationListener);
super.onPause();
}
I am creating an app that only checks for location when user clicks a button.
here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
the location service on the device is enabled.
Thanks very much!
getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.
try this pls
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});
Hie,
I tried this sample code that one of the person who gave me this in my other question in stack overflow. I tried using this code but when i run the applicationn, it doesnt locate my current device and it doesnt even display a dot of my location .. The code does not give me any red underline errors but i am unable to locate the current location i am at.
What did i miss out? is there anyone who has a sample working source code file that i can download from to get my current device location??
the codes i used is as followed,
This is my MainActivity.class
public class MainActivity extends Activity {
MapView mMapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"));
mMapView = new MapView(this);
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location loc){
}
};
MyLocation mylocation = new MyLocation();
mylocation.getLocation(this, locationResult);
}
This is MyLocation.java
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
You have to write the code for displaying a red dot in the gotLocation method which is currently empty. That is why you are not getting anything displayed on top of the map.
I'm beginning in Android programming and I want to get the longitude and latitude of my Android phone, but I read that the Google Longitude API was discontinued. How I can do that now?
Google Longitude was something else. The location API uses LocationManager and has never been deprecated.
This should get you started. Below code gets the location details from NETWORK_PROVIDER. You can use GPS_PROVIDER if you want to get more frequent updates.
LocationManager locmgr = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener loclistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Double lat = (double) (location.getLatitude());
Double lon = (double) (location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,100,loclistener);
Source: Code pulled up from my app which is under development.
Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?
In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.
Dont use the getLastKnownLocation because that could be returning null or old data.
This code Only fetches the location once a button is pressed and not every time. People use to leave the location listener listen in every instance and that kills the battery life so Use the code snippet I have posted by doing lots of research:
// get the text view and buttons from the xml layout
Button button = (Button) findViewById(R.id.btnGetLocation);
final TextView latitude = (TextView) findViewById(R.id.textview4);
final TextView longitude = (TextView) findViewById(R.id.textview5);
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.d("Location Changes", location.toString());
latitude.setText(String.valueOf(location.getLatitude()));
longitude.setText(String.valueOf(location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Status Changed", String.valueOf(status));
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Provider Enabled", provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Provider Disabled", provider);
}
};
// Now first make a criteria with your requirements
// this is done to save the battery life of the device
// there are various other other criteria you can search for..
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
// Now create a location manager
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// This is the Best And IMPORTANT part
final Looper looper = null;
// Now whenever the button is clicked fetch the location one time
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, locationListener, looper);
}
});
First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.
Addition
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);
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
// otherwise wait for the update below
}
else {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
public void onLocationChanged(Location location) {
if (location != null) {
Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
mLocationManager.removeUpdates(this);
}
}
// Required functions
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}