Mohit Suthar
Mohit Suthar

Reputation: 9385

Android StopWatch : Milliseconds with two digit

I have successfully implement stopwatch, but i am not getting proper milliseconds with two digit like this mm:ss.SS 02:54.12, my code is

private Runnable updateTimerThread = new Runnable() {
    public void run() {
        timeMill=timeMill+100;
        updateTime(timeMill);
        stopWatchHandler.postDelayed(this, 100);
    }
};



    private void updateTime(long updatedTime) {
       //I want to convert this updateTime to Milliseonds like two digit 23
}

i have also try this final int mill = (int) (updatedTime % 1000); but this is always getting 10, 20, 30...etc but i want to get 10,11,12,13..so on, if you have any idea about it plz help me.

Upvotes: 0

Views: 2451

Answers (5)

Fletcher Johns
Fletcher Johns

Reputation: 1274

You are incrementing by 100ms. You need to increment by 10ms and post the runnable with a delay of 10ms. You can format the long using SimpleDateFormat.

private Runnable updateTimerThread = new Runnable() {
    public void run() {
        timeMill += 10;
        updateTime(timeMill);
        stopWatchHandler.postDelayed(this, 10);
    }
};

private void updateTime(long updatedTime) {
    DateFormat format = new SimpleDateFormat("mm:ss.SS");
    String displayTime = format.format(updatedTime);
    // Do whatever with displayTime.
}

Be aware that this relies on the delay time of the Handler as a timer. Each repetition will introduce a tiny error. These errors may add up over time, which isn't desirable for a stopwatch.

I would store the time when the stopwatch is started, and calculate elapsed time from that each update:

startTime = System.nanoTime();
//Note nanoTime isn't affected by clock or timezone changes etc

private Runnable updateTimerThread = Runnable() {
    public void run() {
        long elapsedMiliseconds = (System.nanoTime() - startTime()) / 1000;
        updateTime(elapsedMiliseconds);
        stopWatchHandler.postDelayed(this, 10);
    }
};

Upvotes: 3

Masked Man
Masked Man

Reputation: 2548

It's because you update the stopwatch every tenth second in this code stopWatchHandler.postDelayed(this, 100); so it counts like: 0.1, 0.2, 0.3, ...

You should change it to: stopWatchHandler.postDelayed(this, 10);

Upvotes: 0

Rashpal Singh
Rashpal Singh

Reputation: 633

            timeMill=timeMill+100;
            updateTime(timeMill/100);
            stopWatchHandler.postDelayed(this, 10);

Upvotes: 1

Murat Karagöz
Murat Karagöz

Reputation: 37604

stopWatchHandler.postDelayed(this, 100);
timeMill=timeMill+100;

100ms = 0,1s  
10ms = 0,01s

You are updating every tenth second of your timer.

Upvotes: 0

Archana Pareta
Archana Pareta

Reputation: 198

use stopWatchHandler.postDelayed(this, 10);

Upvotes: 0

Related Questions