the code below gives a NullPointerException is there any other way of getting current location in Android application
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = location.getLatitude(); //NullPointerException
double longitude = location.getLongitude();
sure you could use the google play services location API:
http://developer.android.com/google/play-services/location.html
but maybe you should look into your problem first... see this question for your null problem:
android getlastknownlocation returns null
Related
I am trying to track my accurate walking speed. I am using the getSpeed() method of the LocationManager class. The problem is, the speed is not accurate, also answered by AlexWien here . Wein claims "The higher the speed, the more acurate it is. Under 10km/h it does not work well." So what would be the most precise way to do this if getSpeed is not built for precision? I did not stumble upon anything else yet.
// Acquire a reference to the system 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) {
location.getLatitude();
Toast.makeText(context, "Current speed:" + location.getSpeed(),
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
PS:: I understand that both Location and Fine Location permissions are required in this case.
It is very simple.
But I see nothing appears on the logcat.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_selection);
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.
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("MapSelectionActivity", longitude + " " + latitude);
} else {
Log.d("MapSelectionActivity", "location unavailable");
}
}
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);
}
I am sure my phone is connected to a wifi access point, which enables the phone to access the internet.
First change the line below:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
To:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
Like it's said here:
public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
...
minTime minimum time interval between location updates, in milliseconds
...
EDIT
I found this tutorial here, which has a simpler usage:
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this.locationListener);
private final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location locFromGps) {
// called when the listener is notified with a location update from the GPS
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
}
I am in a trouble about using LocationManager in Android.
The Locations from all LocationProvider's getLastKnownLocation are not enough in accuracy.
In my phone, Galaxy S3, 'network' and 'passive' give me the locations when I use the getLastKnownLocation method of the LocationProvider. 'gps' is disabled in my phone. The locations are..
network --> latitude : XX.5511981, longitude : XXX.1284714
passive --> latitude : XX.5511981, longitude : XXX.1284714
Both give me same location information. But the location is very wrong. It is about 50Km wrong location.
In that time, I run the Google maps app in the phone, which reports precise location point. How can the Google maps app obtain the higher precise location information than my app does?
PS. I registered LocationListners for every location provides with '0' minTime and '0' minDistance. But my phone never reports any location changes in several 10 minutes. I think this behavior is acceptable because the phone just stayed in my desk for that duration. But this condition is same for the Google maps app. It reports the phone's location exactly still.
UPDATE.
I tested my code in Galaxy S2. In this case, I requested 3 provides' getLastKnownLocation(GPS, NETWORK, PASSIVE). All the locations was null. And I registered LocationListeners for all the provides. It did not report anything. But in that time, the Google Map apps showed me precise location of the phone. Amazing!. Where does the Google Map apps get location information from?. Following is my test code.
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("location","location chagned x:"+location.getLatitude()+" y:"+location.getLongitude()+" prov:"+location.getProvider());
Date d = new Date(location.getTime());
Log.i("location","date:"+d);
}
public void onProviderDisabled(String provider)
{
Log.i("location","disable:" +provider);
}
public void onProviderEnabled(String provider)
{
Log.i("location","Enable:" +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.i("location","onStatusChanged:" +provider);
}
};
LocationListener locationListenerPassive = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("location","location chagned x:"+location.getLatitude()+" y:"+location.getLongitude()+" prov:"+location.getProvider());
Date d = new Date(location.getTime());
Log.i("location","date:"+d);
}
public void onProviderDisabled(String provider)
{
Log.i("location","disable:" +provider);
}
public void onProviderEnabled(String provider)
{
Log.i("location","Enable:" +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.i("location","onStatusChanged:" +provider);
}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("location","location chagned x:"+location.getLatitude()+" y:"+location.getLongitude()+" prov:"+location.getProvider());
Date d = new Date(location.getTime());
Log.i("location","date:"+d);
}
public void onProviderDisabled(String provider)
{
Log.i("location","disable:" +provider);
}
public void onProviderEnabled(String provider)
{
Log.i("location","Enable:" +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.i("location","onStatusChanged:" +provider);
}
};
void showDebug(String provider)
{
Location location = lm.getLastKnownLocation(provider);
if(location!=null)
{
Log.i("location","all location provider:"+provider+" x:"+location.getLatitude()+" y:"+
location.getLongitude()+" actually provider:"+location.getProvider()+" accuracy:"+location.getAccuracy()+" time:"+location.getTime());
Date d = new Date(location.getTime());
Log.i("location","date:"+d);
if(this.current==null)this.current=location;
else if(this.current!=null && isBetterLocation(location,this.current))this.current=location;
}
else Log.i("location","all location provider:"+provider);
}
void start()
{
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(locationListenerNetwork);
lm.removeUpdates(locationListenerPassive);
lm.removeUpdates(locationListenerGps);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0, 0, locationListenerNetwork);
lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListenerPassive);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
showDebug(LocationManager.NETWORK_PROVIDER);
showDebug(LocationManager.PASSIVE_PROVIDER);
showDebug(LocationManager.GPS_PROVIDER);
}
This is my code. Please tell me y it is not able to calculate the distance.. In this code res is a long variable which is supposed to store the total distance covered. This code is supposed to calculate distance based on GPS as soon as there is a change in the latitude and longitude..
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager;
locationManager= (LocationManager)getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
final Location loc1=locationManager.getLastKnownLocation(provider);
//Location loc1=new Location("");
String netprovider=LocationManager.NETWORK_PROVIDER;
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location loc1)
{
Location loc2=new Location("");
lat2=loc2.getLatitude();
lon2=loc2.getLongitude();
dtvalue.setText(lat1+","+lon1+","+lat2+","+lon2);
Location.distanceBetween(lat1,lon1,lat2,lon2,dist);
res=res+(long)dist[0];
lat1=lat2;
lon1=lon2;
}
public void onProviderDisabled(String provider)
{
// Update application if provider disabled.
}
public void onProviderEnabled(String provider)
{
// Update application if provider enabled.
}
public void onStatusChanged(String provider, int status,
Bundle extras)
{
// Update application if provider hardware status changed.
}
};
locationManager.requestLocationUpdates(provider, 5000, 1, myLocationListener);
locationManager.requestLocationUpdates(netprovider, 5000, 1, myLocationListener);
The problem that you are defining an empty location Location loc2=new Location(""); and then using it.
You can define lat1 and lon1 in your class.
public void onLocationChanged(Location loc1)
{
if(lat1 != 0 && long1 != 0) {
Location.distanceBetween(lat1,lon1,loc1.getLatitude(),loc1.getLongitude(),dist);
res+=(long)dist[0];
}
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
}
I tried to implement the code found in this link location find
The truth is I want to get my location using network or GPS, ( I tested it on Network)
private Location getCurrentLocation(){
// Acquire a reference to the system 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.
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
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);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
}
return lastKnownLocation;
}
How to return the result:
myLocation = getCurrentLocation();
if(myLocation != null)
{
mLatitude = myLocation.getLatitude();
mLongitude = myLocation.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}else {
mLatitude = 36.859502;
mLongitude = 10.168097;
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);}
This wasn't the only code i tried and i dont found any result on a android 2.2 phone.
Any idea about how can i fix it
i check most of the tutorials on the net!!
First check whether did you add the following permissions or not.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
The second thing is that you should give some time to locate location info.You can do that using timer task or posDelayed.
private Location getCurrentLocation(){
// Acquire a reference to the system 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.
t.cancel();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation;
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
this.cancel();
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return lastKnownLocation;
}
},30000);
}
it will give you results after 30seconds.
After a long research, I found my pleasur Here :)
Hope this will help someone.