How to update TextView in activity continuously in an infinite loop?

I have an activity that has a TextView, and I want to constantly update the text.

In Java, I could just create an infinite while loop and just set the text for each iteration.

But when I try to do this in Android, it shows a black screen and does not even load activity.

I put infinity in the onCreate method, maybe that's why it crashes ... but if so, where should I put it?

+7
source share
2 answers

use the Handler and a separate thread / runnable to update the TextView constantly instead of the While loop:

 Handler handler=new Handler(); handler.post(new Runnable(){ @Override public void run() { // upadte textView here handler.postDelayed(this,500); // set time here to refresh textView } }); 
+10
source

Minimal working example based on https://stackoverflow.com/a/312960/216 :

 import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final int i = 0; final TextView textView = new TextView(this); textView.setText(String.format("%d", i)); setContentView(textView); final Handler handler = new Handler(); class MyRunnable implements Runnable { private Handler handler; private int i; private TextView textView; public MyRunnable(Handler handler, int i, TextView textView) { this.handler = handler; this.i = i; this.textView = textView; } @Override public void run() { this.handler.postDelayed(this, 500); this.i++; this.textView.setText(String.format("%d", i)); } } handler.post(new MyRunnable(handler, i, textView)); } } 

You can simply copy it into the main action generated by android create project [...] and you will see the counter in your application.

Tested on Android 22.

0
source

All Articles