0

I'm very new to Android development. Can anyone help me with this snippet, I don't know why it works perfectly although I'm updating my TextView from the worker thread. When I say works perfectly, I mean the TextView shows the value count without any problem. So, My question is - "Is it really possible to update the UI from background thread and if not, where I'm wrong"

public class MainActivity extends AppCompatActivity {
    TextView textView ;
    private int count;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textview);
        btn = findViewById(R.id.startbtn);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                listen();
            }
        });
    }

    public void listen(){
        new Thread(new Runnable() {
            @Override
            public void run()  {
                long time = System.currentTimeMillis();
                while(System.currentTimeMillis()<=time +10000) {
                    count++;
                }
                textView.setText(count+"");
            }
        }).start();
    }
}

1 Answers1

0

Use

runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // Add UI code here

                        }
                    });

All UI updates should be done on the main thread.

  • but why the UI is updating from the background thread without runOnUiThread method. Does it mean, we can update the UI from the background thread. – Anil Joshi May 04 '20 at 09:11