I got a countdown that counts down to a specific date. Each tick (interval 1 second) updates a textbox with the days/hours/minutes left until the event. My problem is that the minutes (don’t know about the days/hours yet) keeps flickering. Meaning it says 18 then 17 then 18 then 17 during the minute before going down to 16 then 17 then 16 and it continues to do like that.
Flickering problem solved, now its just the timezone that is not working. (Flickering was solved using the code from Pshemo)
Also the TimeZone doesn’t appear to be working. It shows 2 hours to much. Have tried to change it using SimpleTimeZone but it doesn’t work, still showing the +2 hours (regardless of the settings on SimpleTimeZone)
What could be the cause?
Countdown code:
new CountDownTimer(remaining, 1000) {
TextView tv = (TextView)getActivity().findViewById(R.id.introTimeLeft);
public void onTick(long millisUntilFinished) {
SimpleTimeZone ts = new SimpleTimeZone(2, "Middle Europe");
Calendar cal = Calendar.getInstance(ts);
cal.set(2012, 5, 28, 17, 0);
long endTime = cal.getTimeInMillis();
long currentTime = System.currentTimeMillis();
long remaining = endTime - currentTime;
tv.setText(getDurationBreakdown(remaining));
}
...
}.start();
public String getDurationBreakdown(long millis)
{
if(millis < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = (long) Math.ceil(TimeUnit.MILLISECONDS.toMinutes(millis));
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes");
return(sb.toString());
}
It is just wild guess but no charm in trying it.
From what I see you read
currentTimeandendTimein same place.You also don’t specify milliseconds in calendar object so
cal.getTimeInMillis()is using current milliseconds. So your codewill sometimes be equal to value like
183360000but also sometimes it will be equalt to value like182999999(depending on how many milliseconds passed between creationendTimeandcurrentTime).This can lead to 1 milliseconds miscalculations but after rounding, it can be also 1 sec/min/hour/day (if this values will be changing in next millisecond).
You can solve it by reading
endTimeonly once, and updating only currentTime while calculatingremaining