1

I am trying to send data from Android app to server .... but on click to save button causes android.os.NetworkOnMainThreadException and app stops. Please can anyone help?

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://farahkhan.byethost15.com/try.php");
try {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
       nameValuePairs.add(new BasicNameValuePair("username", "01"));
       nameValuePairs.add(new BasicNameValuePair("email", signupemailString));

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

       httpclient.execute(httppost);

       signupemail.setText(""); //reset the message text field
        Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Farah
  • 11
  • 4

2 Answers2

0

Replace your code with this:

new Thread(new Runnable() {

                @Override
                public void run() {
                     HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://farahkhan.byethost15.com/try.php");
                try {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                       nameValuePairs.add(new BasicNameValuePair("username", "01"));
                       nameValuePairs.add(new BasicNameValuePair("email", signupemailString));

                       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                       httpclient.execute(httppost);
                       runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                             signupemail.setText(""); //reset the message text field
                        Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();

                        }
                    });

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

                }
            }).start();

and also add a permission in your manifest file:

<uses-permission android:name="android.permission.INTERNET" /> 
Kishan Dhamat
  • 3,746
  • 2
  • 26
  • 36
0

Add internet permission to your manifest file

<uses-permission android:name="android.permission.INTERNET" /> 

After that Check this answer

Community
  • 1
  • 1
Samy Massoud
  • 4,295
  • 2
  • 35
  • 48