How to Update UI from UI thread or Background thread. runonuithread() method in android. Threads in Android . How to update Ui from background Thread.

1] In the worker thread use the runonUithread() method and pass it a runnable.

YOU CANNOT ACESS runonuithread() method OUTSIDE THE ACTIVITY/MAIN ACTIVITY ,to acess outside the Activity , you need a  reference of the mainActivity.



class Worker implements Runnable{

@Override
public void run() {
int i=0;
while (i< 10){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("MyTag","Started : " + Thread.currentThread().getName()+ " Counter at : " + i);
i++;
}
//This part runs of the Main thread and makes changes to the Ui
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("Keyy",Thread.currentThread().getName());
TextView textView = findViewById(R.id.textview_display);
textView.setText(" Hello World ! ");
}
});
}
}
}

(A shortcut to run on new thread using Java Thread class)

public void setTextAfter5Sec(View view) {


// Using JAVA Thread class for threading
new Thread(new Runnable() {
@Override
public void run() {

// Creating a new worker thread
try {
Thread.sleep(5000);
Log.d(TAG, "setTextAfter5Sec : "+Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}

// Using runOnUiThread since we worker thread cannot touch Ui directly.
runOnUiThread(new Runnable() {
@Override
public void run() {
textview.setText("5 seconds completed !");
Log.d(TAG, "setTextAfter5Sec : "+Thread.currentThread());
}
});

}
}).start();

}



useful video : https://youtu.be/Tzf-sPm5eTo



































Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)