Showing posts from March, 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

classMyTaskextendsAsyncTask{publicinterfaceOnUpdateListener{publicvoid onUpdate(MyObject obj);}OnUpdateListener listener;MyTask(){}publicvoid 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

MyActivityextendsActivity{void onCreate (Bundle savedInstanceState){super.onCreate(savedInstanceState);MyTask task =newMyTask(); task. setUpdateListener(newMyTask.On…