I am trying to Develop a Vehicle Tracking app where I want to track Drivers activity Like DISTANCE, TIME TAKEN , AVRAGE SPEED. I am able to Track his current location and also see the path the Driver is going on in firebase database, Now I have found a code from a project for Distance, I have implemented it in my project.and the app is crashing, is there a different way to get and calculate distance, stopwatch, speed??
public void newJourney(){
locations = new ArrayList<Location>();
}
public float getDistanceOfJourney(){
if (locations.size() <=1){
return 0;
}
return locations.get(0).distanceTo(locations.get(locations.size() - 1)) / 1000;
}
protected void onStart() {
super.onStart();
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
startLocationUpdates();
}
initButtons();
/////////NEW ///////////////////////
new Thread(new Runnable() {
@Override
public void run() {
float d = (float) getDuration();
long duration = (long) d; // in seconds
float distance = getDistanceOfJourney();
long hours = duration / 3600;
long minutes = (duration % 3600) / 60;
long seconds = duration % 60;
float avgSpeed = 0;
if(d != 0){
// avgSpeed = distance / (d / 3600);
}
final String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
final String dist = String.format("%.2f KM", distance);
final String avgs = String.format("%.2f KM/H", avgSpeed);
postBack.post(new Runnable() {
@Override
public void run() {
durationText.setText(time);
avgSpeedText.setText(avgs);
distanceText.setText(dist);
}
});
try {
Thread.sleep(500);
} catch (Exception e){
e.printStackTrace();;
}
}
}).start();
}
after running this code am getting this error in log
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.example.vehicletracker.MapsActivity.getDistanceOfJourney(MapsActivity.java:116)
at com.example.vehicletracker.MapsActivity$3.run(MapsActivity.java:293)
at java.lang.Thread.run(Thread.java:923)
Below is the Code of tracking the current Activity and updating it in realtime:
@Override
public void onLocationChanged(@NonNull Location location) {
if (location != null) { //location is enabled
saveLocation(location);
} else { //When user has no access to location
Toast.makeText(this, "No Location", Toast.LENGTH_LONG).show();
}
//polylines
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
polypoints.add(latLng);
redrawLine();
//newUpdate
if (recordLocations){
locations.add(location);
}
}
private void saveLocation(Location location) {
databaseReference.setValue(location); //Saving Location of user To db
}