If you want to do it in a clean way, try the following approach
First create an enumeration that contains all your asynchronous call names
public enum TaskType { USER_LOGIN(1), GET_PRODUCTS(2), GET_EMPLOYEE(3); int value; private TaskType(int value) { this.value = value; } }
Then create an interface
public interface AsyncTaskListener { public void onTaskCompleted(String result, TaskType taskType); }
Now we implement this interface in the activity that you are going to call GetAsyncTask for example: -
public class LoginActivity extends Activity implements AsyncTaskListener { protected void onCreate(Bundle savedInstanceState) { String url = "....."; new GetAsyncTask(LoginActivity.this, LoginActivity.this, TaskType.USER_LOGIN).execute(url); } ... public void onTaskCompleted(String result, TaskType taskType) { if(taskType == TaskType.USER_LOGIN){
Finally, this is your AsyncTask
public class GetAsyncTask extends AsyncTask<String, Void, String> { String outputStr; ProgressDialog dialog; Context context; AsyncTaskListener taskListener; TaskType taskType; public GetAsyncTask(Context context, AsyncTaskListener taskListener, TaskType taskType){ this.context = context; this.taskListener = taskListener; this.taskType = taskType; } @Override protected void onPreExecute() { super.onPreExecute(); dialog = ProgressDialog.show(context, "Loading", "Please wait...", true); } @Override protected String doInBackground(String... params) { String urlString = params[0]; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); }
source share