i want to update my textview every second. on button click i am calling one method,
loopMethod(milli); //suppose milli= 50000 i.e 50 sec.
so my loopMethod(int m)
is as follows:
public void loopMethod(int m){
timer=(TextView) findViewById(R.id.timerText);
if(m>=1000){
try {
timer.setText(""+m);//timer is a textview
System.out.println(m);
m=m-1000;
Thread.sleep(1000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
loopMethod(m);
}
}
so what i am expecting is, my timer textview
should print the value of m
every second. but i am getting only console output i.e system.out.println(m)
... printing value on console working fine... but its not updating my textview at all
You can use following code:
Runnable updater;
void updateTime(final String timeString) {
timer=(TextView) findViewById(R.id.timerText);
final Handler timerHandler = new Handler();
updater = new Runnable() {
@Override
public void run() {
timer.setText(timeString);
timerHandler.postDelayed(updater,1000);
}
};
timerHandler.post(updater);
}
In this line:
timerHandler.post(updater);
time will set for the first time. i.e, updater will execute. After first execution it will be posted after every 1 second time interval. It will update your TextView every one second.
You need to remove it when the activity destroys, else it will leak memory.
@Override
protected void onDestroy() {
super.onDestroy();
timerHandler.removeCallbacks(updater);
}
Hope it will help you.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments