使用asynctask发送数据时强制关闭

时间:2013-03-25 05:05:52

标签: android

我使用asynctask将http发送到服务器。我把传递参数放到我的asynctask。这是我的asynctask

private class ProcessSend extends AsyncTask<String, Boolean, String> {

        //private HttpClient mHc = new DefaultHttpClient();
        HttpClient httpclient = new DefaultHttpClient();
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(MainPetakTetap.this);
            pDialog.setMessage("Loading Send ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

        }
        @Override
        protected String doInBackground(String... params) {
            publishProgress(true);
            // Do the usual httpclient thing to get the result
            String code = params[0];
            String alamat = params[1];
            String batas = params[2];
            String lat = params[3];
            String lon = params[4];
            String luas = params[5];
            String tglA = params[6];
            String tglB = params[7];
            String userId = params[8];
            //Toast.makeText(MainPetakTetap.this, "response : " + name, Toast.LENGTH_LONG).show();
            String url;
            url = CGlobalConfig.getURLRcvrPetakTetap();
            // Create a new HttpClient and Post Header

            HttpPost httppost = new HttpPost(url);

            //This is the data to send
            //String MyName = "puja"; //any data to send

            try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("code", code));
            nameValuePairs.add(new BasicNameValuePair("alamat", alamat));
            nameValuePairs.add(new BasicNameValuePair("info_batas", batas));
            nameValuePairs.add(new BasicNameValuePair("lat", lat));
            nameValuePairs.add(new BasicNameValuePair("lon", lon));
            nameValuePairs.add(new BasicNameValuePair("luas", luas));
            nameValuePairs.add(new BasicNameValuePair("tgl_awal", tglA));
            nameValuePairs.add(new BasicNameValuePair("tgl_akhir", tglB));
            nameValuePairs.add(new BasicNameValuePair("user_id", userId));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request

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

            //This is the response from a php application
            final String reverseString = response;
            runOnUiThread(new Runnable() {
                  public void run() {
                      Toast.makeText(MainPetakTetap.this, "response : " + reverseString, Toast.LENGTH_LONG).show();
                  }
                });

            //saveContact(code);
            } catch (final ClientProtocolException e) {
                runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(MainPetakTetap.this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
                      }
                    });
            // TODO Auto-generated catch block
            } catch (final IOException e) {
                runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(MainPetakTetap.this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
                      }
                    });
            // TODO Auto-generated catch block
            }

            // stop gps
            lman.removeUpdates(locaListener);
            constantsCursor.requery();
            return null;
        }

        @Override
        protected void onProgressUpdate(Boolean... progress) {
            // line below coupled with 
            //    getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS) 
            //    before setContentView 
            // will show the wait animation on the top-right corner
            MainPetakTetap.this.setProgressBarIndeterminateVisibility(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            publishProgress(false);
            pDialog.dismiss();
            // Do something with result in your activity
        }

    }

但是当显示进度对话框发送时,toast显示Succes但强制关闭。这是我的logcat

03-25 11:57:40.320: ERROR/AndroidRuntime(5704): FATAL EXCEPTION: AsyncTask #1
03-25 11:57:40.320: ERROR/AndroidRuntime(5704): java.lang.RuntimeException: An error occured while executing doInBackground()
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.lang.Thread.run(Thread.java:1019)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.ViewRoot.requestLayout(ViewRoot.java:629)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.widget.ScrollView.requestLayout(ScrollView.java:1299)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.view.View.requestLayout(View.java:8267)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.widget.AbsListView.requestLayout(AbsListView.java:1124)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:790)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:31)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.widget.CursorAdapter$MyDataSetObserver.onChanged(CursorAdapter.java:385)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:31)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.database.AbstractCursor.requery(AbstractCursor.java:97)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.database.sqlite.SQLiteCursor.requery(SQLiteCursor.java:548)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at hariff.ltis.petaktetap.MainPetakTetap$ProcessSend.doInBackground(MainPetakTetap.java:484)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at hariff.ltis.petaktetap.MainPetakTetap$ProcessSend.doInBackground(MainPetakTetap.java:1)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-25 11:57:40.320: ERROR/AndroidRuntime(5704):     ... 4 more

如何解决这个问题?

将ui线程从后台的Do移动到onPostExecute?但是如何?

2 个答案:

答案 0 :(得分:1)

您需要将对cursor.requerry的调用移动到onPostExecute。该游标绑定到列表适配器,因此它调用UI代码。你只能在主线程上做到这一点。

答案 1 :(得分:1)

而不是runOnUiThread(),只需返回错误消息并在onPostExecute()中捕获,然后您可以检查结果是否为null,如果不是,则显示Toast并做其他的事情。此外,最好移动

        lman.removeUpdates(locaListener);
        constantsCursor.requery();

onPostExecute()