0

如何将“尝试”放在 onclicklistener 中,以便当我按下按钮时它会发送数据?但是我这样做,当我运行它时它总是崩溃。

 @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 中的“尝试”时会出现问题?

4

1 回答 1

2

您需要在按钮上添加点击侦听器,然后将所有 http 请求内容放入其 onClick 方法中:

b1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
});
于 2012-03-12T07:47:58.400 回答