javaandroidhttpandroid-studiosendasynchronousrequest

Android HTTP: Make more than 1 asynctask request


I followed this post to set up an Http Async Request: HttpRequest

So, now, I call: new DownloadTask().execute("http://www.google.com/"); to make this request.

How can I manage different calls? For example:

new DownloadTask().execute("http://www.google.com/");
new DownloadTask().execute("http://www.facebook.com/");
new DownloadTask().execute("http://www.twitter.com/");

And have different results?


Solution

  • Pass one more argument to the AsyncTask. Make some constants corresponding to your tasks.

    new DownloadTask().execute("http://www.google.com/", DownloadTask.ID_ASYNC1);
    new DownloadTask().execute("http://www.facebook.com/", DownloadTask.ID_ASYNC2);
    new DownloadTask().execute("http://www.twitter.com/", DownloadTask.ID_ASYNC3);
    

    Inside AsyncTask, use this id to identify which is the request being called.

    private class DownloadTask extends AsyncTask<String, Void, String> {
        //Variable for storing the req id
        private int id;
    
        //Constants corresponding to your tasks
        public static int ID_ASYNC1 = 0;
        static static int ID_ASYNC1 = 0;
        static static  int ID_ASYNC1 = 0;
    
        @Override
        protected String doInBackground(String... params) {
            id = params[1]);
            //your code
        }
    
        @Override
        protected void onPostExecute(String result) {
            if(id == ID_ASYNC1){
                //Do your task #1
            } else if(id == ID_ASYNC2){
                //Do your task #2
            }
        }
    }