-1

I have a countdown timer that I have created (before you suggest the built in one, I have unsolved problems with that in the past). Clearly I'm just not formatting this correctly, but I just can't seem to get it to go "mm:ss" for my data. Instead I get "mmmmmmm:ss". Where did I go wrong?

TimerTask mTimerTask;
final Handler handler = new Handler();
Timer t = new Timer();
private long nCounter = 180000;
int minutes;
int seconds;

public void doTimerTask(){

    mTimerTask = new TimerTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {

                    if(nCounter<=0){
                        stopTask();
                        return;
                    }
                    nCounter--;
                   //  seconds = (int) ((nCounter / 1000) % 60);
                 //    minutes = (int) ((nCounter / 1000) / 60);
                    seconds = (int)(nCounter) % 60 ;
                   minutes = (int)((nCounter-seconds)/60);

                    // update TextView
                    timerTextView.setText(String.format("%d:%02d", minutes, seconds));

                }
            });
        }};

    // public void schedule (TimerTask task, long delay, long period)
    t.scheduleAtFixedRate(mTimerTask,0,1000);

}
Community
  • 1
  • 1
Kat
  • 2,460
  • 2
  • 36
  • 70
  • Initially `nCounter = 180000`. The `minutes` equals `180000/60`, so the display will be `3000:00`. How many minutes do you want to count down from? – goofyz Apr 30 '15 at 03:29
  • I"m starting from 3 minutes, so that's in milliseconds – Kat Apr 30 '15 at 12:40

1 Answers1

0

This behavior is as expected. You are using "%d:%02d" which displays your digits as-is in the minute part. But even if you use "%02d:%02d" you will still not see your time formatted as mm:ss because your minutes is larger than the scope of the format (i.e 3000 if nCounter is 180000). In case of "%02d" you will only see the effect if the number is below 10 (e.g 9 will be printed as 09).

Also you shouldn't cast int from long because it's unsafe. You might see the result suddenly turn negative if the original value is larger than maximum int. You should use long or int only for all your needs here.

inmyth
  • 8,880
  • 4
  • 47
  • 52
  • So, if I shouldn't do this... what *should* I do to get the mm:ss? – Kat Apr 30 '15 at 12:39
  • 1
    You already do it on the ss part but you cannot do it on the mm part because the range of your minutes is much wider than 0-99. – inmyth Apr 30 '15 at 14:50