David David - 3 months ago 11
Java Question

Count up numbers in a specific time period, Java, Android

How do I make a count up in TextView from

0
to a
number
in 5 seconds?

The
number
variable will always have different value, thats why I need it to always count up from
0
to
number
in 5 seconds.

If i do a
while
and the
number
= 1982654324441 it will take to long to count it up.

This is how I do it now:

new Thread(new Runnable() {
public void run() {
while (counter < number) {
try {
Thread.sleep(0,01);
} catch (InterruptedException e) {
e.printStackTrace();
}

textView.post(new Runnable() {
public void run() {
textView.setText("" + counter);
}
});
counter++;
}
}
}).start();

Answer

Try this method: It should work for all numbers > 0 and you can also adjust the update interval.

final int TIME_TO_COUNT = 5000; //ms
//Update interval in ms. Consider that the screen cannot be updated as often as you want.
//17ms (about 60FPS) sound reasonable
final int UPDATE_INTERVAL = 17;
final int number = 5001; //Can be any number between 0 and Integer.MAX_VALUE;

new Thread(new Runnable() {
    public void run() {
        double counter = 0.0;
        while (counter < number) {
            try {
                Thread.sleep(UPDATE_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            textView.post(new Runnable() {
                public void run() {
                    textView.setText(String.valueOf(Math.ceil(counter)));
                }
            });
            counter += (number / (double) TIME_TO_COUNT) * UPDATE_INTERVAL;
        }
    }
}).start();
Comments