3

This is a possible duplicate of Sending POST data in Android

I used this code to send post data to server using android

public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.mysite.com/android.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
            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
        }
    } 

But when I run this app it shows this error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.senddata/com.example.senddata.MainActivity}: android.os.NetworkOnMainThreadException

Whats problem? Can anyone help?

Community
  • 1
  • 1
Zahid Habib
  • 715
  • 3
  • 12
  • 23

3 Answers3

4

Try using the below code inside your mainactivityactivity below setContentView() to avoid networkOnmainThread exception..

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

But, doing heavy operation inside background thread using AsyncTask without blocking main thread would be great!

And also refer this link...

AsyncTask Android example

Community
  • 1
  • 1
Hariharan
  • 24,741
  • 6
  • 50
  • 54
1

Call the postData using an asyntask, in the doInBackground of asyntask. Do not call it from the mainThread

ShineDown
  • 1,881
  • 3
  • 21
  • 29
0

You can't do Networking related tasks on Main Thread use AsyncTask Class instead