jsandv
jsandv

Reputation: 306

Multiple http request Android

During syncronization I have to clear the online stream, and then load all the data line by line using HTTP requests. One request per data line. It is important that the http requests are run in the sequence they are created.

Main class:

       //Sync cloud stream
            HttpAsyncTask hats = new HttpAsyncTask();
            hats.execute(app.getProductCartStream().getClearUri());

            for(int i = 0 ; i<app.getProductCartData().size();i++){
                ArrayList<String> values = new ArrayList<String>();
                values.add(app.getProductCartData().get(i));
                String insertUri = app.getProductCartStream().getInsertUri(values);
                HttpAsyncTask hat = new HttpAsyncTask();
                hat.execute(insertUri);
            }

Private class:

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
    try{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urls[0]);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null; ) {
            builder.append(line).append("\n");
        }
        return builder.toString();
    }catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();;
    }
    return null;
}

@Override
protected void onPostExecute(String result) {
    if(result!=null){
        Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(getApplicationContext(), "Not able to save data", Toast.LENGTH_LONG).show();
    }

}

}

Question 1: Will the requests be executed in the order they are created? I.e it is very important that the firts http request clears the stream first.

Question 2: All the HTTP stuff i deprecated. What is the correct way to do it now?

Question 3: Why can't i fire the syncronized code in application.onDestroy()?

Upvotes: 0

Views: 64

Answers (1)

Androider
Androider

Reputation: 3873

Ans.1:- Yes in new AsyncTask().execute(), all requests are handled sequentially. For parallel execution we have call another method.

Ans.2: HTTP stuff i deprecated, like DefaultHttpClient, even in Android M they are not present therefore avoid them and use better method of like:

HttpURLConnection connection = (HttpURLConnection)url.openConnection();

...bla bla bla.

but deprication doesn't mean that your method will not work.

Ans3: I'm unable to get your question.

Thanks

Upvotes: 1

Related Questions