Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update textView from thread

In my OnCreate method I have created a thread that listens to incoming message!

In OnCreate() {

//Some code

myThread = new Thread() {

            @Override

            public void run() {

                receiveMyMessages();

            }
        };
myThread.start();

// Some code related to sending out by pressing button etc.

}

Then, receiveMyMessage() functions…

Public void receiveMyMessage()
{

//Receive the message and put it in String str;

str = receivedAllTheMessage();

// <<    here I want to be able to update this str to a textView. But, How?
}

I checked this article but it did not work for me, no luck!

like image 801
Droid-Bird Avatar asked Mar 23 '11 02:03

Droid-Bird


1 Answers

Any updates to the UI in an Android application must happen in the UI thread. If you spawn a thread to do work in the background you must marshal the results back to the UI thread before you touch a View. You can use the Handler class to perform the marshaling:

public class TestActivity extends Activity {
    // Handler gets created on the UI-thread
    private Handler mHandler = new Handler();

    // This gets executed in a non-UI thread:
    public void receiveMyMessage() {
        final String str = receivedAllTheMessage();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // This gets executed on the UI thread so it can safely modify Views
                mTextView.setText(str);
            }
        });
}

The AsyncTask class simplifies a lot of the details for you and is also something you could look into. For example, I believe it provides you with a thread pool to help mitigate some of the cost associated with spawning a new thread each time you want to do background work.

like image 135
CalloRico Avatar answered Nov 01 '22 17:11

CalloRico