tom91136 tom91136 - 7 months ago 28
Java Question

Return a value from AsyncTask in android

one simple question:

is it possible to return a variable in Async task?

//my async task is in outer class

private class myTask extends AsyncTask<Void,Void,Void>{

public myTask() {
super();
}

protected Void doInBackground(Void... params) {

//do stuff
return null;
}

@Override
protected void onPostExecute(Void result) {
//do stuff
//how to return a variable here?
}
}

// The asyncTask is started from activity
myTask.execute()
// something like this?
myvalue = myTask.getvalue()


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:


The point of async task is that the task is
asynchronous
, meaning that after you call
execute()
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).

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.

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.

Answer

Why not call a method that handles the value?

public class MyClass extends Activity {

    private class myTask extends AsyncTask<Void, Void, Void> {

        //initiate vars
        public myTask() {
            super();
            //my params here
        }

        protected Void doInBackground(Void... params) {
            //do stuff
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //do stuff
            myMethod(myValue);
        }
    }

    private myHandledValueType myMethod(Value myValue) {
        //handle value 
        return myHandledValueType;
    }
}
Comments