IllegalStateExcaption:无法执行活动的方法

时间:2014-04-24 07:28:55

标签: android

在我的应用程序中,我想在按钮点击时发送httpRequest。 我的按钮的点击事件是clickButton。我的代码就像:

public void clickButton(View v){
    Toast.makeText(getApplicationContext(), "Inside Button Click", Toast.LENGTH_LONG).show();
    orderNumber=(EditText) findViewById(R.id.order_no);
    deliverTime=(EditText) findViewById(R.id.delivery_time);
    String id=orderNumber.getText().toString();
    String tim=deliverTime.getText().toString();

    Log.i("Button Click Value", "inside post"+tim);
    String toPass="url?id="+id+"&time="+tim;

        // TODO Auto-generated method stub

        Log.i("xxxxxxxx", "inside post");
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(toPass);

            Log.i("Http Request", "sending req"+toPass);
            HttpResponse response = client.execute(request);
        } catch (Exception e) {
            Log.e("Problem in connection", e.toString());
        }

    Intent intent=new Intent(getBaseContext(), MyRestaurantActivity.class);
    startActivity(intent);
}

但即使是第一个吐司也没有显示,应用程序突然停止。 请帮助我摆脱这个问题。

1 个答案:

答案 0 :(得分:0)

您无法在MainThread上执行与网络相关的操作。

使用AsyncTask,如下所示:

class CallNetworkOperation extends AsyncTask<String, Integer, String> {

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
        ProgressDialog progress = new ProgressDialog(YourActivityname.this);
    progress.setTitle("Sending Mail");
                progress.setMessage("Please Wait...");
              progress.show();

}

@Override
protected String doInBackground(String... params) {
       try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(toPass);

        Log.i("Http Request", "sending req"+toPass);
        HttpResponse response = client.execute(request);
    } catch (Exception e) {
        Log.e("Problem in connection", e.toString());
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
             progress.dismiss();
       Intent intent=new Intent(getBaseContext(), MyRestaurantActivity.class);
   startActivity(intent);
      }
 }