Zahid Habib
Zahid Habib

Reputation: 715

Android Send Post Data To Server

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?

Upvotes: 3

Views: 10106

Answers (3)

Mayank Mishra
Mayank Mishra

Reputation: 31

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

Upvotes: 0

ShineDown
ShineDown

Reputation: 1879

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

Upvotes: 1

Hariharan
Hariharan

Reputation: 24853

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

Upvotes: 4

Related Questions