0

Here is the my post request code. please help me debug this one. thanks. i can run my application but it doesnt give out errors.

public void ibutton4Click()
    {
           {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("10.0.0.1/cgi-bin/ForwardPress.cgi");
                try {

                  HttpResponse response = client.execute(post);
                  BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                  String line = "";
                  while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                  }

                } catch (IOException e) {
                    startActivity(new Intent(this,MainActivity.class));
                }
              }
    }
shikurin03
  • 13
  • 3
  • You're executing a long-lasting task on the main UI thread. You have to do these things in the background so the UI keeps functioning in the meanwhile. – Jeroen Vannevel Apr 14 '14 at 01:27
  • background? like putting it inside an Asynctask? – shikurin03 Apr 14 '14 at 01:28
  • I'm not familiar with the exact Android implementation but yes, from first glance that looks exactly like what you want. *AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.* – Jeroen Vannevel Apr 14 '14 at 01:29

1 Answers1

0

For more on NetworkOnMainThread error and why is it that way,
1. Responsive UI in design and interaction
2. More on the Adroid class
3. Useful SO link

To fetch the data in a separate thread,

1. Write custom Asynctasks:
AsyncTask Dev Reference
AsyncTask Android example

OR

2. Use something like AsyncHttpClient: http://loopj.com/android-async-http/
where you get onSuccess and onFailure methods to work with the response.

The option 2. is better if you just want to fetch data without doing anything else, and work on it, or save it. For the same, you need to parse the response first.

Community
  • 1
  • 1
Pararth
  • 8,114
  • 4
  • 34
  • 51