Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to textView.setText from Thread?

I need to set text to textView from thread. All code is created in oncreate()

something like

public TextView pc;

    oncreate(..) {
        setContentView(R.layout.main);
        pc = new TextView(context);
        Thread t =new Thread() {
            public void run() {
                pc.setText("test");
        }};
        t.start();

This crashes my app. How can I set text from thread?

like image 736
POMATu Avatar asked May 18 '11 19:05

POMATu


2 Answers

Use a Handler:

public TextView pc;
Handler handler = new Handler();
oncreate(..) {
    setContentView(R.layout.main);
    pc = new TextView(context);
    Thread t =new Thread(){
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    pc.setText("test");
                }
            });
        }
    }};
    t.start();
}

But you have another problem. pc points to a view that is not part of your hierarchy. You probably want to use findViewById with the id of the TextView in your layout.

like image 159
Ted Hopp Avatar answered Oct 22 '22 23:10

Ted Hopp


Try Activity.runOnUiThread().

Thread t = new Thread() {
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pc.setText("test");
            }
        });
    }
};
like image 10
bigstones Avatar answered Oct 23 '22 00:10

bigstones