Monday, June 8, 2015

Android: AsyncTask delegate

Let say we have an Activity that wants to receive a messages from AsyncTask.


We create an Interface AsyncResponse

public interface AsyncResponse {
   void publishLog(String logContent);
}

We create our AsyncTask:

public class FileReaderTask 
 extends AsyncTask < Void, Void, List < AbstractX > > {
// delegate should be set in the Activity   
public AsyncResponse delegate = null;
String xyz = "";

// ...

@Overrideprotected void onPreExecute() {
   delegate.publishLog(xyz);
}

@Overrideprotected void onPostExecute(List x) {
...
      delegate.publishLog(xyz);
   }
}

Now we can tie together the AsyncTask and Activity:

public class FileReaderActivity extends Activity implements AsyncResponse {

   private static final String TAG = FileReaderActivity.class.getCanonicalName();
   FileReaderTask asyncTask = new FileReaderTask();

   private TextView logText;

   /**    * Called when the activity is first created.    */  

 @Override   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      logText = (TextView) findViewById(R.id.logText);

      // tell Async Task that this Activity will listen      

asyncTask.delegate = this;
      asyncTask.execute();
   }

   /**    * This method will receive log from Async Task.    * @param logContent    */   

@Override   public void publishLog(String logContent) {
      logText.append(logContent);
   }
}


If you like this post, please give me your 2 cents ($0.02 litterally) to show token of appreciation and encourage me to write more:

Donate Bitcoins