Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView Timer

For my Android application there is a timer that measures how much time has passed. Ever 100 milliseconds I update my TextView with some text like "Score: 10 Time: 100.10 seconds". But, I find the TextView only updates the first few times. The application is still very responsive, but the label will not update. I tried to call .invalidate(), but it still does not work. I don't know if there is some way to fix this, or a better widget to use.

Here is a example of my code:

float seconds;
java.util.Timer gametimer;
void updatecount() { TextView t = (TextView)findViewById(R.id.topscore);
t.setText("Score: 10 - Time: "+seconds+" seconds");
t.postInvalidate();
}
public void onCreate(Bundle sis) {
... Load the UI, etc...
  gametimer.schedule(new TimerTask() { public void run() {
     seconds+=0.1; updatecount();
} }, 100, 100);
}
like image 964
Isaac Waller Avatar asked Feb 07 '09 00:02

Isaac Waller


3 Answers

The general solution is to use android.os.Handler instead which runs in the UI thread. It only does one-shot callbacks, so you have to trigger it again every time your callback is called. But it is easy enough to use. A blog post on this topic was written a couple of years ago:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html

like image 138
Ben Bederson Avatar answered Oct 25 '22 12:10

Ben Bederson


What I think is happening is you're falling off the UI thread. There is a single "looper" thread which handles all screen updates. If you attempt to call "invalidate()" and you're not on this thread nothing will happen.

Try using "postInvalidate()" on your view instead. It'll let you update a view when you're not in the current UI thread.

More info here

like image 31
haseman Avatar answered Oct 25 '22 10:10

haseman


Use Below code to set time on TextView

public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        @Override
        public void onFinish() {

            ExamActivity.this.submitresult();
        }

        @Override
        public void onTick(long millisUntilFinished) {

            long millis = millisUntilFinished;

            int seconds = (int) (millis / 1000) % 60;
            int minutes = (int) ((millis / (1000 * 60)) % 60);
            int hours = (int) ((millis / (1000 * 60`enter code here` * 60)) % 24);

            String ms = String
                    .format("%02d:%02d:%02d", hours, minutes, seconds);
            txtimedisplay.setText(ms);
        }
    }
like image 33
Jotiram Chavan Avatar answered Oct 25 '22 10:10

Jotiram Chavan