Mueyiwa Moses Ikomi Mueyiwa Moses Ikomi - 20 days ago 5
Android Question

How to calculate time difference between 2 objects in an ArrayList

i'm sorry if the title doesn't coincide with the request but thats the best i could come up with at the time.

So i have an ArrayList that takes an object as parameter.

private List<Movement> walked = new ArrayList<>();


Note: Movement is the name of the class
I have a method that calculates the time difference between two time strings and it works wonderfully.

My dilemma is that when i click a button, an object is added to the ArrayList. i want to know the time duration between this new click, and the next click as the time of both actions in being recorded.

i'm doing stuff like this in my onClickListener

Movement move = new move();
move.setTime("current time");
walked.add(move);


So based on the number of clicks, i want to be able to get the objects in the list, get their respective time and calculate the time difference for each and output it as i click on.

My function for doing the time calculations works i'm just unable to iterate properly. This is what ive tried;

for(Movement x:walked){
Toast(TimeCal.getDuration(x.getTime(), "i'm to put the previous object time here") + " min(s)");
}


Any help will be appreciated.

Answer

In order to compare the current click to previous click in one loop, you shouldn't use a foreach but rather a for loop. Something along these lines:

if(walked.size() > 0)
for(int i = 1; i < walked.size(); i++) { 
    Movement current = walked.get(i); 
    Movement prev = walked.get(i-1);
    Toast(TimeCal.getDuration(current.getTime(), prev.getTime()) + " min(s)") 
}