I am developing an Android application which requires the use of AsyncTask for Network connection. I called it from the main thread. So the doInBackground method runs and then returns to the onPostExecute method. After the onPostExecute method is executed, I want to return a value back to the activity from where it was called, as I have to some operation in that particular activity which requires the value returned from onPostExecute method. How do I solve this? How do I return a value from onPostExecute ?
Thanks in Advance
AsyncTask, as its name stated, is running asynchronously with UI thread, the onPostExecute method will be called at some point in the future, when doInBackground finished. We don't care when onPostExecute method will be called (actually there is no way to tell at project build time), the only thing we care is onPostExecute method is guaranteed to be called properly by underlying framework at some point in the future. So the purpose of onPostExecute method is for processing result returned from worker thread, this is also why the only argument of onPostExecute method is the result returned from doInBackground method.
I have to some operation in that particular activity which requires the value returned from onPostExecute method. How do I solve this?
Of cause, you can create some instance variables (or use listerner pattern) in the Activity class store the result when returned and ready in onPostExecute method. The problem is you never know when this result is ready outside onPostExecute method at project build time, as it is actually determined at app runtime. Unless you write some waiting mechanism continuously polling the result, which resulting sacrifice the benefit of AsyncTask, for instance, the built-in API AsyncTask.get() which makes AsyncTask running synchronously with UI thread and return the result to the Activity.
The best practice is change your design and move the operation code which requires the result returned from AsyncTask into onPostExecute method. hope this helps.
you can use getter and setter for getting value back from AsyncTask
public class MainActivity extends Activity {
public String retunnumfromAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layouttest);
new Asyntask(this).execute();
}
public class Asyntask extends AsyncTask<Void, Void, String> {
private final Context Asyntaskcontext;
public Asyntask(Context context){
Asyntaskcontext = context;
}
@Override
protected void onPostExecute(String result) {
MainActivity mainactivity = (MainActivity) Asyntaskcontext;
mainactivity.retunnumfromAsyncTask = result;
super.onPostExecute(result);
}
}
}
Just write the AsyncTask class as inner class to your activity then, declare whatever the value you want to return as global. Was it helpful to you?