two dependent HttpUrlConnection with AsyncTask in android

771 views Asked by At

I am developing an application with android, I am new to it in one part of my projects I need to get the data from input fields from users, then creates a Http connection to server and put the result of the first call along with some other fields into another Http connection to Server, I don't know what is the right approach to implement it.

public class TwoHttpActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_transport);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}
public static class PlaceholderFragment extends Fragment {

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

         button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                params[0] = firstText;
                .   .   .   .
                .   .   .   .
                params[3] = secondText;
            }
        });
     }
}

The Question: Now I need params[0] to be sent to one url http://myserver/urlOne and then get the result from the server and put them along with params[1] to params[3] and send them together to the second url of server http://myserver/urlTwo

Since these connections should be made inside classes extends from AsyncTask then I think it's not possible to just have

public class FirstUrlTask extends AsyncTask<String[], Void, Void> {
  //the class handles the call to first url inside
  //doInBackground(String[]... params) 
}

and

public class SecondUrlTask extends AsyncTask<String[], Void, Void> {
       //the class handles the call to second url inside
  //doInBackground(String[]... params) 
    }

and then

 firstUrlTask.execute(..); 
 secondUrlTask.execute(..);

inside button.setOnClickListener(new View.OnClickListener()

Since they are asynchronous task it's not clear which tasks will be executed first, so please help me with the right approach to do this, please provide your answer with detailed information and code sample.

3

There are 3 answers

0
Pankaj On BEST ANSWER

Do it like this:

First Step: Call FirstUrlTask Async Class

firstUrlTask.execute(..); 

Second Step: Call SecondUrlTaskAsync Class in onPostExecute() of FirstUrlTask

public class FirstUrlTask extends AsyncTask<String[], Void, Void> {

  //doInBackground(String[]... params) {}  

   protected void onPostExecute(ClassTypeYouReturning result){
      super.onPostExecute();
      secondUrlTask.execute(..);   //Call to second url 
   }
}

The above approach will ensure that the first call will be made to first url and on the response of first url, the second url will be called.

1
A.S On

from what i understood you need to call FirstUrlTask and then it will retrieve data from the server and after that you need to pass these data into the SecondUrlTask to perform another action that depend on the data retrieved from the first asyncTask, you can simply call your first task into your onClickListener() and then call the second on in onPostExecute() method of the first one

0
Mithun On

You can have only one AsyncTask depending upon your data to be downloaded (if 2 tasks wouldn't take long). See below code snippet for AsyncTask. For passing values to your AsyncTask, you can either pass it as arguments, such as, your_async_task.exectue(your_array_of_strings) or you can use the constructor to pass your values.

class SingleAsyncTask extends AsyncTask<String, Void, Void> {

    final String[] params;

    public SingleAsyncTask() {
        // default constructor
    }

    public SingleAsyncTask(String... params) {
        this.params = params;
    }

    // the class handles the call to first url inside
    // doInBackground(String[]... params)

    @Override
    protected Void doInBackground(String... params) {
        if (params != null && params.length > 0) {
            // #STEP 1
            String param0 = params[0];
            // make request to 1st URL http://myserver/urlOne

            // #STEP 2
            // when you get a success for 1st URL fire the request for 2nd URL
            // I consider it as 3 as per your problem statement but you can tune
            // as it suites you
            if (params.length > 3) {
                String param1 = params[1];
                // and so on
                // fire request for http://myserver/urlTwo along with result you obtained in step1
            }
        }

        // but try-catch blocks for above statements, as per exceptions you
        // think you need to handle and return final result for "onPostExecute"


        // default return could be null
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // notify your UI
    }

}

Hope this helps!