I'm currently trying to develop a running tracker on Android Studio, and I'm using a normal technique to get the distance and then turning it into miles rather than meters and I'm doing it inside of a service. However, it starts spurting out random long numbers when I start the emulated route. I know its to do with how I'm calculating the distance using distanceTo(), but no clue how to fix it. Not posting the entire code, but the relevant parts are blow
@Override
public void onCreate() {
super.onCreate();
Log.d("G53", "onCreate called");
locationListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5, 5, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
oldLocation = location;
} catch (SecurityException e) {
Log.d("g53mdp", e.toString());
}
}
public double getDistance() {
if(running) {
distance = distance * 0.000621371192;
Log.d("tag", " " + distance);
return distance;
}
return 0;
}
public void startExercise() {
Log.d("tag", "startExercise called");
startTime = System.currentTimeMillis();
stopTime = 0;
running = true;
distance = 0;
}
public void stopExercise() {
Log.d("tag", "stopExercise called");
running = false;
startTime = 0;
}
public class MyLocationListener extends Binder implements LocationListener, IInterface {
@Override
public void onLocationChanged(Location location) {
if(running) {
distanceInMetres = oldLocation.distanceTo(location);
if (distanceInMetres < 10) {
Log.i("DISTANCE", "Values too close, so not used.");
} else {
distance += distanceInMetres;
oldLocation = location;
}
}
}
The output in Logcat looks like this
I have 2 thoughts.
I read your code, and your conversion for miles into meters is ok.
1.- I think the problem is you're reutilizing the distance variable in 2 or many methods, creating the overflow.
You are adding a distance here.
distance += distanceInMetres;
That is perfect, but then you read that variable and assign them a new value in
public double getDistance() {
if(running) {
distance = distance * 0.000621371192;
Log.d("tag", " " + distance);
return distance;
}
return 0;
}
So I suggest you change getDistance()
into
public double getDistance() {
if(running) {
return distance * 0.000621371192;
}
return 0;
}
And in that way, you no reassign values.
2.- Another possible issue could be a concurrence issue, but you need to post more about your code to follow.