从Android应用程序发送数据到服务器时查找异常

时间:2014-05-04 11:28:56

标签: android networkonmainthread

我正在尝试将数据从Android应用程序发送到服务器....但是点击保存按钮会导致android.os.NetworkOnMainThreadException和应用程序停止。 请任何人帮忙吗?

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();
}

2 个答案:

答案 0 :(得分:0)

用以下代码替换您的代码:

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();

并在清单文件中添加权限:

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

答案 1 :(得分:0)

为您的清单文件添加互联网权限

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

之后检查this answer