androidandroid-asynctaskcommonsware

Getting results from an AsyncTask


I'm trying to use AsyncTask to download a string and return the string. I want to use AsyncTask because it might take a while.

One problem is that nowhere on the internet can I find an example of an AsyncTask returning any kind of value. So I took the example in the Commonsware book and modified it to return a value and I get the value as follows:

String mystr = new AddStringTask().execute().get();

While this works, it seem that this line of code is waiting for the return value and therefore synchronous. There must be some way to have an event trigger with the results of the AddStringTask.

How is that done? Thanks, Gary


Solution

  • An AsyncTask cannot return a value, because to get the returned value you would have to wait before the task is finished. That would make the AsyncTask meaningless.

    Instead, you should move your code in onPostExecute() (which runs on the UI thread, if this is what you worry about). This is where you handle the value returned by doInBackground() and typically update the UI or show an error message.