1

我对 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;
    }
}

}

4

1 回答 1

3

您不能更新与自身Thread不同的UI 元素UI Thread。您必须使用Handler或使用runOnUiThread

例如

runOnUiThread(new Runnable() {
      public void run() {
         label.setText("Please Work");
       }
 });
于 2013-05-08T10:12:46.747 回答