Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async HTTP post android

I am using an application where i just need to download a pair of coordinates for google maps from a mysql server. I can do this successfully using php and a normal httpost but my app freezes for a few seconds when i do it.

I read that you need to make httppost asycronous in order to avoid that freezing until the server finishes the prossess and sends the results.

The point is that i need that results in a json array like the normal httpost.

For example if i had this httppost.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

String result11 = null;
// convert response to string
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is11, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line = "0";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is11.close();
    result11 = sb.toString();
} catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
}

// parsing data
try {
    JSONArray jArray1 = new JSONArray(result11);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

How can i convert that to an asynchronous post so i can avoid the freeze ?

like image 365
user878813 Avatar asked Mar 18 '26 21:03

user878813


1 Answers

There is a nice class AsyncTask which can be used to easily run asynchronous tasks. If you embed your code in such a subclass, you might end up with this:

public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
    @Override
    protected JSONArray doInBackground(Void... params) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
            String result11 = sb.toString();

            // parsing data
            return new JSONArray(result11);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        if (result != null) {
            // do something
        } else {
            // error occured
        }
    }
}

You can start the task using:

new FetchTask().execute();

Additional resources:

  • Painless Threading - developer.android.com
  • AsyncTask - developer.android.com
like image 186
SecStone Avatar answered Mar 21 '26 11:03

SecStone