如何在onclicklistener中放置“try”,所以当我按下按钮时它会发送数据?但是我这样做,它在运行时总会崩溃。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (EditText) findViewById(R.id.name);
pass = (EditText) findViewById(R.id.password);
b1 = (Button) findViewById(R.id.btn);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www2.park.se/~ts5124/receive.php");
try {
JSONObject json = new JSONObject();
json.put("name","Tim");
json.put("password", "hje");
StringEntity se;
se = new StringEntity(json.toString());
// Add your data
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
Log.i(TAG, json.toString());
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (JSONException je) {
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
之前我已经完成了按钮并且它已经工作了,为什么在onClick中“尝试”时会出现问题?
答案 0 :(得分:2)
您需要在按钮上添加点击侦听器,然后将所有http请求内容放入其onClick方法中:
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});