本文介绍了在OnclickListener AsyncTask的崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很新到Android希望你有人可以帮助我。
每当我使用OnclickListener来执行的AsyncTask,程序会崩溃。如果我不使用onclicklistener执行的AsyncTask,测试程序工作正常。
I am very new to Android hope you anyone could help me.Whenever I use an OnclickListener to execute an Asynctask, the program will crash. If I execute the Asynctask without using onclicklistener, the testing program works fine.
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;
}
}
}
推荐答案
您不能更新在主题从
iteself。你必须使用 UI线程
不同的UI元素处理程序
或使用 runOnUiThread
you can not update UI element in a Thread
different from the UI Thread
iteself. You have to use an Handler
or use runOnUiThread
例如
runOnUiThread(new Runnable() {
public void run() {
label.setText("Please Work");
}
});
这篇关于在OnclickListener AsyncTask的崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!