Saturday, March 21, 2015

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) {
listener.onUpdate(obj);
}
}

}

In Activity, we can get the object by

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

Reference: http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a

1 comment:

Androidians