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);
}
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
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With