gpt4 book ai didi

android - 异步任务在 OnclickListener 中崩溃

转载 作者:行者123 更新时间:2023-11-29 18:00:30 28 4
gpt4 key购买 nike

我是 Android 的新手,希望有人能帮助我。每当我使用 OnclickListener 执行 Asynctask 时,程序就会崩溃。如果我在不使用 onclicklistener 的情况下执行 Asynctask,测试程序工作正常。

public class MainActivity extends Activity {

TextView label;
Button start;
MyAsyncTask test;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

label = (TextView)findViewById(R.id.tvIndicator);
start = (Button)findViewById(R.id.btSend);

test = new MyAsyncTask();

start.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.execute();
}
});
}

public class MyAsyncTask extends AsyncTask{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("htt://****.php");//left out the address

@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub

label.setText("Please Work");

String MyName = "testing";
String response = null;
try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("emailAdd", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);

label.setText(response.length());
return response;

} catch (Exception e) {
e.printStackTrace();
}

return null;
}
}

最佳答案

您不能在不同于 UI Thread 本身的 Thread 中更新 UI 元素。您必须使用 Handler 或使用 runOnUiThread

例如

runOnUiThread(new Runnable() {
public void run() {
label.setText("Please Work");
}
});

关于android - 异步任务在 OnclickListener 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16438016/

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