How to update a TextView in an activity constantly in an infinite loop?

10,110

Solution 1

use Handler and a separate thread/runnable for updating TextView constantly instead of 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
    }
});

Solution 2

Minimal working example

Based on https://stackoverflow.com/a/14295193/895245:

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 just copy paste this into the main activity generated by android create project [...], and you will see a counter on your app.

Tested on Android 22.

Share:
10,110
aclowkay
Author by

aclowkay

Scala,Java, Spark and such

Updated on June 16, 2022

Comments

  • aclowkay
    aclowkay almost 2 years

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

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

    But when I try to do that in Android, it shows a black screen, and doesn't even load the activity.

    I put the infinite in the onCreate method, perhaps that's why it crashes..but if it is, where should I put it?

  • MattD
    MattD about 10 years
    If you are going to refer to handler as part of that closure, you need to delcare it final.