Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use runOnUiThread() or onPostExecute() to update the UI within a thread

Tags:

java

android

I have a class ConnectionThread that extends Thread. I am passing the context to it's constructor and i want to invoke a method that enables and disables all the buttons on the UI. This method is in the same class - ConnectionThread. Also i want to popup a Toast in a try catch block in case the connection can't be established.

public ConnectionThread(Context context, BluetoothSocket bluetoothSocket,
        Button connectButton, Button disconnectButton,
        Button throttleUpButton, Button throttleDownButton,
        Button moveForwardButton, Button moveBackwardButton,
        Button moveLeftButton, Button moveRightButton, Button exitButton) {

My question is how can i use runOnUiThread() or onPostExecute() to do that?

like image 444
Ted Tedson Avatar asked Jan 24 '26 01:01

Ted Tedson


1 Answers

onPostExecute()(only in Asynctask) runs already on UI thread so no need to create a runOnUiThread inside of it.. In other case if you are inside a thread or background task and want to update some views now you need to call the runOnUiThread because you are now leaving the main thread..

pass the activity instance to the contructor to call the main thread.

example:

activity.runOnUiThread(new Runnable() {
  public void run() {
    //code here
  }
});
like image 158
Rod_Algonquin Avatar answered Jan 26 '26 18:01

Rod_Algonquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!