How to update textview variable every 5 seconds
Possible duplicate:
Updating the TextView every N seconds?
Here I want to update the Hr value in the text view as soon as it is calculated for each iteration, but with a delay of 2 seconds each time. I do not know how to do that. What I get now in the textview is the last iteration value. I want all values ββto be displayed with a constant delay. all help pls.
for(int y=1;y<p.length;y++)
{
if(p[y]!=0)
{
r=p[y]-p[y-1];
double x= r/500;
Hr=(int) (60/x);
Thread.sleep(2000);
settext(string.valueof(Hr));
}
}
+3
source to share
5 answers
public class MainActivity extends Activity{
protected static final long TIME_DELAY = 5000;
//the default update interval for your text, this is in your hand , just run this sample
TextView mTextView;
Handler handler=new Handler();
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.textview);
handler.post(updateTextRunnable);
}
Runnable updateTextRunnable=new Runnable(){
public void run() {
count++;
mTextView.setText("getting called " +count);
handler.postDelayed(this, TIME_DELAY);
}
};
}
I was hoping that this time you get into the code and run it.
+4
source to share
use Handler
or TimerTask(with runOnUiThread())
instead of a loop to update the text every 5 seconds like this:
Handler handler=new Handler();
handler.post(runnable);
Runnable runnable=new Runnable(){
@Override
public void run() {
settext(string.valueof(Hr)); //<<< update textveiw here
handler.postDelayed(runnable, 5000);
}
};
+2
source to share
lets us just hope it helps you enough
import java.awt.Toolkit;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class demo
{
Toolkit toolkit;
Timer timer;
public demo()
{
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new scheduleDailyTask(), 0, //initial delay
2 * 1000); //subsequent rate
}
class scheduleDailyTask extends TimerTask
{
public void run()
{
System.out.println("this thread runs for every two second");
System.out.println("you can call this thread to start in your activity");
System.out.println("I have used a main method to show demo");
System.out.println("but you should set the text field values here to be updated simultaneouly");
}
}
public static void main(String args[]) {
new demo();
}
}
0
source to share