I want to update a TextView
from an asynchronous task in an Android application. What is the simplest way to do this with a Handler
?
There are some similar questions, such as this: Android update TextView with Handler, but the example is complicated and does not appear to be answered.
However, note that you cannot update the UI from any thread other than the UI thread or the "main" thread. To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: Activity.
Android handles all the UI operations and input events from one single thread which is known as called the Main or UI thread. Android collects all events in this thread in a queue and processes this queue with an instance of the Looper class.
Use Cases of HandlerThread They are useful when you need to implement a Producer/Consumer paradigm between different threads. It simplifies the creation of the Looper instance that is bound to a specific thread. It is used in the Android Service implementation in order to execute some tasks off of the main thread.
In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });
There are several ways to update your UI and modify a View
such as a TextView
from outside of the UI Thread. A Handler
is just one method.
Here is an example that allows a single Handler
respond to various types of requests.
At the class level define a simple Handler
:
private final static int DO_UPDATE_TEXT = 0;
private final static int DO_THAT = 1;
private final Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
final int what = msg.what;
switch(what) {
case DO_UPDATE_TEXT: doUpdate(); break;
case DO_THAT: doThat(); break;
}
}
};
Update the UI in one of your functions, which is now on the UI Thread:
private void doUpdate() {
myTextView.setText("I've been updated.");
}
From within your asynchronous task, send a message to the Handler
. There are several ways to do it. This may be the simplest:
myHandler.sendEmptyMessage(DO_UPDATE_TEXT);
You can also update UI thread from background thread in this way also:
Handler handler = new Handler(); // write in onCreate function
//below piece of code is written in function of class that extends from AsyncTask
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(stringBuilder);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With