How to use callback or interface - Pass data from Asynctask to activity

To get data from a separate thread to the the main UI thread which will be in different stand alone class can get the result through callbacks. Consider AsyncTask in a separate stand alone class and we need to get data from AsyncTask to the Activity, we can get it through callbacks. The steps are as,

1. Define an interface in AsyncTask
2. Pass the object of interface when calling AsyncTask from Activity
3. In AsyncTask onPostExecute() pass the result to activity

class MyTask extends AsyncTask {
public interface OnUpdateListener {
public void onUpdate(MyObject obj);
OnUpdateListener listener;
MyTask() {
public void setUpdateListener(OnUpdateListener listener) {
this.listener = listener;
MyObject doInBackground() {
return obj;
onPostExecute(MyObject obj) {
if (listener != null) {


In Activity, we can get the object by

MyActivity extends Activity {
void onCreate (Bundle savedInstanceState) {
MyTask  task = new MyTask();
task. setUpdateListener(new MyTask. OnUpdateListener() {
public void onUpdate(MyObject obj) {



Post a Comment

Popular posts from this blog

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture

AlarmManager and Notification in Android