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



As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles