2

I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?

3 Answers3

3

It won't work sometimes as it is not thread safe. Thus, it is recommended to use handler or runonuithead.

Anandu R
  • 56
  • 5
1

Android doesnt check every where whether its UI thread or Not so in some cases it might work .but its never thread safe.The preferred way is to display in UIThread.

Rockin
  • 723
  • 4
  • 25
  • 51
0

Another way to do UI operations safety outside main UI thread.

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
           mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
        }
    });
Dimon
  • 790
  • 1
  • 10
  • 24