1

The value returned only can be used on the postexecute method?

When I call the doInBackground method I get the source code (String) of a webpage. I want return that source code to my main activity because there I classify the information within the source code. But I'm thinking I can't do that.. can I?

From the postexecute, could I return it?

  • 1
    The reason you can't return it is due to the AsyncTask being asynchronous. Where would you save the value if you returned it? The code that invoked the AsyncTask should be executed by now, as well as a number of other instructions. – jcxavier Apr 23 '12 at 16:33

2 Answers2

0

In the onPostExecute method, you could assign it to a member variable on your activity, or call some other method with it as an argument.

Update per comment: You can declare the subclass of AsyncTask declared in another file, but you will not be able to manipulate member variables of the enclosing activity directly. You can, however, define interface to glue together your activity and the AsyncTask defined elsewhere, and pass in a reference to activity to the AsyncTask in the constructor.

wsanville
  • 37,158
  • 8
  • 76
  • 101
  • Ok! Another think related with the scope: I can have the AsyncTask extended class in other file, or it must be in the same file? –  Apr 23 '12 at 16:41
  • _you could assign it to a member variable on your activity_, the problem here is from outside onPostExecute method, you never know when this variable is set and ready (determined at runtime) at the time you writing your code at project build time. I have written a detailed [answer](http://stackoverflow.com/questions/10115243/after-asynctask-execute-do-x-from-activity/10115881#10115881) explain this before, worth to check it out. – yorkw Apr 23 '12 at 22:00
0

The variables of the AsyncTask are removed, when the task is completed.

However, you can set a class variable of the executing class from onPostExecute:

@Override
protected void onPostExecute(Integer result) {
        integerListInExecutingClass = result;                   
        super.onPostExecute(result);
}

But this method only works, if you declare the AsyncTask as a private class inside the executing class.

Zento
  • 335
  • 1
  • 8