1

我正在尝试将数据从 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();
}
4

2 回答 2

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" /> 
于 2014-05-04T11:31:08.063 回答
0

将 Internet 权限添加到清单文件

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

之后检查这个答案

于 2014-05-04T11:31:20.710 回答