Issue
I have an activity class which is calling background AsyncTask twice like
BackgroundTask bt1 = new BackgroundTask(this, ApiHelper.GET);
bt.execute(url1);
BackgroundTask bt2 = new BackgroundTask(this, ApiHelper.POST, params);
bt.execute(url2);
one is used to GET the data and another is used to POST the data to server.
Constructors of this AsyncTask is as follows
public BackgroundTask(Context context, String method) {
this.context = context;
this.method = method;
this.callback = (onBackgroundTaskListener<String>) context;
}
public BackgroundTask(Context context, String method, ArrayList<NameValuePair> params) {
this.context = context;
this.method = method;
this.callback = (onBackgroundTaskListener<String>) context;
this.params = params;
}
Now MainActivity.class is implemented by onBackgroundTaskListener<String>
interface as
public interface onBackgroundTaskListener<T> {
void onTaskComplete(T result);
}
onPostExecute of AsyncTask class, String result
is returned or passed back to the calling class, shown below.
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
callback.onTaskComplete(result);
}
Now I have one method (onTaskComplete) in MainActivity to tackle two responses coming from one background task. I would like to use the condition to figure out which execution is returned a result like...
@Override
public void onTaskComplete(String result) {
if (execution == 1) {
// Parse the GET result
} else if(execution == 2) {
// Parse the POST result
}
}
I don't want to implement the multiple AsyncTask and would like to achieve it using single AsyncTask and called this AsyncTask multiple times within single activity. What should be the possible way to implement this.
Solution
enum BackgroundType{ GET, POST }
public interface onBackgroundTaskListener<T> {
void onTaskComplete(T result, BackgroundType type);
}
--------------------------
BackgroundTask bt1 = new BackgroundTask(this, ApiHelper.GET, GET);
bt.execute(url1);
BackgroundTask bt2 = new BackgroundTask(this, ApiHelper.POST, params, POST);
bt.execute(url2);
------------------------
@Override
public void onTaskComplete(String result, BackgroundType type) {
switch(type){
case GET:
break;
case POST:
break;
}
}
Answered By - Amani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.