Search code examples
javaandroidmultithreadingviewandroid-handler

How is it possible to do UI operations outside the UI thread?


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?


Solution

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