Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn a value from AsyncTask in Android
    text
    copied!<p>One simple question: is it possible to return a value in <code>AsyncTask</code>?</p> <pre><code>//AsyncTask is a member class private class MyTask extends AsyncTask&lt;Void, Void, Void&gt;{ protected Void doInBackground(Void... params) { //do stuff return null; } @Override protected void onPostExecute(Void result) { //do stuff //how to return a value to the calling method? } } </code></pre> <p>And then within my <code>Activity</code>/<code>Fragment</code>:</p> <pre><code>// The task is started from activity myTask.execute() // something like this? myvalue = myTask.getvalue() </code></pre> <p><strong>EDIT: This was asked a long time ago where I wasn't familiar with Java, now that I'm better with it, I 'll do a quick summary:</strong></p> <p>The point of async task is that the task is <code>asynchronous</code>, meaning that after you call <code>execute()</code> on the task, the task starts running on a thread of its own. returning a value from asynctask would be pointless because the original calling thread has already carried on doing other stuff (thus the task is asynchronous). </p> <p>Think of time: At one point of time, you started a task that will run in parallel with the main thread. When the parallel-running task completed, time has also elapsed on the main thread. The parallel task cannot go back in time to return a value to the main thread.</p> <p>I was coming from C so I didn't know much about this. But it seems that lots of people are having the same question so I thought I would clear it up a bit.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload