Reputation: 1731
I am looking for some advise about the following, I have a HttpUtil class (util) in which I have my sendGetRequest- and sendPostRequest methods. I use them to perform a successfull login to a website from which I am going to fetch some data. Now, I call these methods in my MainActivity in a Asynctask:
protected Boolean doInBackground(Void... params) { try { //1. GET request util.sendGetRequest(loginURL, null); //2. Post request util.sendPostRequest(loginURL, null); //3. Final GET request util.sendGetRequest(resultURL, null); // Read stream String[] response = util.readMultipleLinesRespone(); for (String line : response) { System.out.println(line); } } catch (InterruptedException e) { return false; } catch (Exception e) { e.printStackTrace(); } }
I am looking for a solution so that one waits for another to finish (1st get then post, finally get), if it`s possible I want to keep this util.class intact and not put everything in the Asynctask (doInBackground). Is this possible or do I have the wrong approach?
Your opinions and advise please.
Thank you in advance.
Upvotes: 0
Views: 83
Reputation: 1470
Your HttpUtil class should somehow signal that the response is received. For example, put this code in HttpUtil to signal end of operation:
synchronized (this) {
done = true;
notifyAll();
}
and this code will wait for the operation to end:
while(!util.isDone()) {
try {
synchronized(util) { util.wait(); }
} catch(Exception e) { ... }
}
Upvotes: 0
Reputation: 1370
You can have two AsyncTasks. One for get and other for post. First execute get request. Then in onPostExecute of the first AsyncTask execute the second AsyncTask that sends the post request in doInBackground();
Upvotes: 0
Reputation: 5626
The approach I normally use is this:
Using this approach should really make your life easier - specifically helps you know when something is completed and so you can proceed with the next task as needed.
Good luck!
Upvotes: 1