Reputation: 381
I'm trying to solve this problem that doesn't seem to be working for me as I crack my head over it. It seems that the while loop doesn't loop properly.
Say I click a button, and here is my code:
Calendar now = Calendar.getInstance();
Calendar later = Calendar.getInstance();
later.add(Calendar.SECOND, 120);
Label1.setText(String.valueOf(later.get(Calendar.MINUTE)));
Label2.setText(String.valueOf(later.get(Calendar.SECOND)));
while ((now.get(Calendar.MINUTE) <= later.get(Calendar.MINUTE)) && (now.get(Calendar.SECOND) <= later.get(Calendar.SECOND))){
Label3.setText(String.valueOf(now.get(Calendar.SECOND)));
Label4.setText(String.valueOf(now.get(Calendar.MINUTE)));
//try {
//Thread.sleep(500);
//} catch (InterruptedException e1) {
//// TODO Auto-generated catch block
//e1.printStackTrace();
//}
now = Calendar.getInstance();
}
I tried WITH and WITHOUT Thread.sleep(500).
WITH = All 4 labels update, but application becomes unresponsive. WITHOUT = All 4 labels update, with Label1 properly showing it is 2 minutes ahead. But the while loop just stops there and Label3 and Label4 does not update further.
This is just a test code for my main application, my main application is quite similar, just that instead of updating a label, I am supposed to Blink a light. The problem is that the blinking usually stops prematurely!
Thanks!
Upvotes: 1
Views: 514
Reputation: 10161
It is better to compare calendars using Calendar#compareTo()
method:
while (now.compareTo(later) < 0) {
...
}
In your case you can start your loop at 10:59:59 and it will exit immediately, because 11:00:00 does not satisfy your condition.
Upvotes: 2
Reputation: 16392
think your loop logic is wrong. You loop as long as the now minutes and seconds are both less than the corresponding values for later. Problem is that it's possible you want to continue if the now seconds are more than the later seconds if the minutes are not the same. Hope that made sense.
so now= 12 sec 40 min and later = 10 sec 41 min
would drop out and you don't want it to.
Upvotes: 0