gpt4 book ai didi

java - 我如何让按钮执行这个方法

转载 作者:行者123 更新时间:2023-12-01 23:44:14 27 4
gpt4 key购买 nike

这可能是一个 super 简单的答案,但当我按下按钮时,我的应用程序崩溃了。这是我尝试运行单击按钮的方法:

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

我确定我有:

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

这是我的主要 Activity :

 <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="16dp"
android:onClick="postData"
android:text="Button" />

最佳答案

方法的签名应该是

public void postData(View v)

另一件事,你不能在主 UI 线程中执行网络操作。使用AsyncTask相反

关于java - 我如何让按钮执行这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com