0

In my android application, I want to strictly follow the Android guidelines. So after executing the AsyncTask, I have 2 options to update the UI with the results.

  1. I can either send the results back the main thread using a call-back listener and update the UI from there.
  2. I can also pass a reference of the desired UI elements to AsyncTask and update these elements in onPostExecute.

So, which approach is better and why?

Sharjeel
  • 15,588
  • 14
  • 58
  • 89
allstraws
  • 129
  • 3
  • 12

3 Answers3

1

You have to actually understand Threading, if it is a simple call-back listener, it won't change the thread in which the code is running. If this is the case, then methods (1) and (2) would be more or less the same.

If you are actually referring to using a Handler, then it has some differences, a Handler actually queue up the callback and call it later in the Thread in which the Handler is created.

However, as OnPostExecute is already in UI Thread, it means it is ok to update UI element as (2). And the most important point you should be aware is that your Activity could be destroyed at the time OnPostExecute is called. If so, you should not modify the UI with the Activity reference which the AsyncTask is created with.

Derek Fung
  • 8,171
  • 1
  • 25
  • 28
0

Background tasks that are long are run on onBackground function of AsyncTask. At the end of onBackground, onPostExecute is called where you should do UI changes.

It works fine if you have your AsyncTask inside your Activity. You can just update UI views inside onPostExecute since you have access to them.

When your AsyncTask is a separate class and you don't have access to UI views of your Activity then inside your onPostExecute function you can return results to your Activity and update UI there.

Sharjeel
  • 15,588
  • 14
  • 58
  • 89
  • How to return results to your activity by onPostExecute() when Async is declared in another file ?? – Sanjeev Sep 20 '15 at 04:16
  • Easiest way is to use an event bus. Try looking at Otto, it's only couple of lines of code http://square.github.io/otto/ – Sharjeel Sep 20 '15 at 04:53
0

Both cases work well if you want to update your ui after a task finishes. onPostExecute also processes code in the main thread. Which approach is better? It depends on how you want to organize your code structure.

  1. If you just want to update your UI. I think it's better to update them inside onPostExecute, because your code would be more simple and clear.
  2. However, using a callback is more flexible. Since you can do what ever you want with the task result according to your passing callback.
Rodson
  • 566
  • 4
  • 10