I want to get my result from an Async task. If I use task.execute.get, my UI will be frozen. I want my Async task will be stand alone class so I don't want to put my result processing code in onPostExecute. I've found some information about call back data from Async task here: http://blog.evoxmusic.fr/content/how-implement-callback-asynctask
and here: android asynctask sending callbacks to ui
but the problem is:
1-I don't know when to process the result?
2-why to use interface?
3-What's the differences of using an interface with simply putting the result in a public field in Async task from onPostExecute?
This is my Async class:
public class AsyncCallWs extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public String methodName="";
private WebService ws;
private ArrayList<ServiceParam> paramsList;
private boolean hasParams;
public AsyncCallWs(Activity activity,String methodName) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
hasParams = false;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
public AsyncCallWs(Activity activity,String methodName,ArrayList<ServiceParam> params) {
xLog.position();
try {
this.dialog = new ProgressDialog(activity);
this.methodName = methodName;
this.paramsList = params;
hasParams = true;
} catch (Exception e) {
xLog.error(e.getMessage());
}
}
@Override
protected void onPreExecute() {
this.dialog.setMessage(PersianReshape.reshape("Loading..."));
this.dialog.show();
}
@Override
protected String doInBackground(String... params) {
xLog.position();
String result = "No async task result!";
try {
ws = new WebService(PublicVariable.NAMESPACE, PublicVariable.URL);
if (!hasParams){
result = ws.CallMethod(methodName);
}
else{
xLog.info("THIS METHOD IS: "+ methodName);
result = ws.CallMethod(methodName,paramsList);
xLog.info("THIS RESULT IS: "+ result);
}
} catch (Exception e) {
xLog.error(e.getMessage());
}
return result;
}
@Override
protected void onPostExecute(String result) {
xLog.position();
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
xLog.info("Output of current AsyncTask is:"+ result);
}
}
For your concern with basics ..
Step (1) Initiate Async Task
Step (2) Create your AsyncTask class like this
Hope it clears all your doubts..
The result will be processed in
onPostExecute
, which in turn will call your interface method in whatever class is implementing this interface. So the actual UI stuff will all take place in yourActivity
orFragment
or whatever is implementing the interface callback. You can pass any data you want to it.An interface is a great way to decouple the logic from your
AsyncTask
and whatever class (I assume anActivity
orFragment
) that is implementing it. Also this means that any class that implements this interface can process results from thisAsyncTask
, it become easily re-usable.You still won't get a callback - how will your
Activity
orFragment
know when this field is populated and ready to be interrogated?