9

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.

Community
  • 1
  • 1
David Manpearl
  • 12,362
  • 8
  • 55
  • 72

2 Answers2

22

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);
Irving
  • 767
  • 1
  • 8
  • 10
  • 5
    What about `Handler class should be static otherwise memory leaks might occur` warning? – nmxprime Jul 03 '14 at 09:16
  • 1
    please find the [**Blog post**](http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html) and this answer ( http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler) to get more insight on this – Renjith K N Nov 18 '15 at 08:26
  • i recommend weakHandler here to avoid a leak. https://github.com/badoo/android-weak-handler – j2emanue Jan 05 '17 at 17:02
4

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);
    }
});
HB.
  • 4,116
  • 4
  • 29
  • 53