Updating the UI from a Background Thread

suggest change

It is common to use a background Thread for doing network operations or long running tasks, and then update the UI with the results when needed.

This poses a problem, as only the main thread can update the UI.

The solution is to use the runOnUiThread() method, as it allows you to initiate code execution on the UI thread from a background Thread.

In this simple example, a Thread is started when the Activity is created, runs until the magic number of 42 is randomly generated, and then uses the runOnUiThread() method to update the UI once this condition is met.

public class MainActivity extends AppCompatActivity {

    TextView mTextView;

    protected void onCreate(Bundle savedInstanceState) {
        mTextView = (TextView) findViewById(R.id.my_text_view);

        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    //do stuff....
                    Random r = new Random();
                    if (r.nextInt(100) == 42) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        mTextView.setText("Ready Player One");

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents