0

Possible Duplicate:
android.os.NetworkOnMainThreadException

My android app works on emulator but in phone it shows android.os.NetworkOnMainThreadException. From search I came to know that it can be cleared using AsyncTask. Can any body help me to create an AsyncTask which calls httppost on button click and give back the response to onCreate?

Community
  • 1
  • 1

1 Answers1

0

I did it and here is the code

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
  String response = "";
  for (String url : urls) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse execute = client.execute(httpGet);
      InputStream content = execute.getEntity().getContent();

      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
      String s = "";
      while ((s = buffer.readLine()) != null) {
        response += s;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  return response;
}

@Override
protected void onPostExecute(String result) {
  textView.setText(result);
}

}