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