无法修复android中的Future Task异常

时间:2013-07-22 07:11:23

标签: android json multithreading android-asynctask http-post

我在android编程方面很新,而且我正在尝试编写一些代码,其中包括 Httppost,Json,AsyncTask 等等。我收到错误但我不能解决它。

public void onClick(View v) {

            MainActivity.this.runOnUiThread(new Runnable() {

                public void run() {
                    RequestLogInFromServer RL = new RequestLogInFromServer();
                    RL.execute().toString();

                }
            });
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public class RequestLogInFromServer extends
        AsyncTask<Object, Object, Object> {
    TextView txt = (TextView) findViewById(R.id.textView1);
    EditText edt = (EditText) findViewById(R.id.editText1);

    @Override
    protected Object doInBackground(Object... params) {

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(
                "http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
        httpPost.setHeader("Content-type", "application/json");

        try {

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            is = resEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            // strJson = null;
        }
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"), 8); // iso-8859-1 //
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
            is.close();
            strJson = sb.toString();
        } catch (Exception e) {

        }

        try {
            if (strJson != null) {
                jObj = new JSONObject(strJson);
                String text = jObj.get("masterPerosActive").toString();
                edt.setText(text);

            } else {
                jObj = null;
            }
        } catch (JSONException e) {
        }
        return "Executed";
    }

这是例外-log cat

07-22 09:51:36.791: E/AndroidRuntime(13010): FATAL EXCEPTION: AsyncTask #1
07-22 09:51:36.791: E/AndroidRuntime(13010): java.lang.RuntimeException: An error occured while executing doInBackground()
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.lang.Thread.run(Thread.java:882)
07-22 09:51:36.791: E/AndroidRuntime(13010): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4634)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.view.View.invalidate(View.java:10193)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.invalidateRegion(TextView.java:4375)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.invalidateCursor(TextView.java:4318)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.spanChange(TextView.java:7172)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:8759)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.Selection.setSelection(Selection.java:76)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.Selection.setSelection(Selection.java:87)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.setText(TextView.java:3535)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.setText(TextView.java:3405)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.EditText.setText(EditText.java:80)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.widget.TextView.setText(TextView.java:3380)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at com.example.test2.MainActivity$RequestLogInFromServer.doInBackground(MainActivity.java:113)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-22 09:51:36.791: E/AndroidRuntime(13010):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-22 09:51:36.791: E/AndroidRuntime(13010):    ... 5 more
07-22 09:51:36.851: W/IInputConnectionWrapper(13010): showStatusIcon on inactive InputConnection
07-22 09:53:22.261: D/ActivityThread(13141): handleResumeActivity now pri:0
07-22 09:53:22.261: D/ActivityThread(13141): handleResumeActivity set pri:0
07-22 09:53:27.531: W/dalvikvm(13141): threadid=11: thread exiting with uncaught exception (group=0x40d9a318)
07-22 09:53:27.561: E/AndroidRuntime(13141): FATAL EXCEPTION: AsyncTask #1
07-22 09:53:27.561: E/AndroidRuntime(13141): java.lang.RuntimeException: An error occured while executing doInBackground()
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.lang.Thread.run(Thread.java:882)
07-22 09:53:27.561: E/AndroidRuntime(13141): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4634)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.view.View.invalidate(View.java:10193)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.invalidateRegion(TextView.java:4375)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.invalidateCursor(TextView.java:4318)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.spanChange(TextView.java:7172)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:8759)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.Selection.setSelection(Selection.java:76)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.Selection.setSelection(Selection.java:87)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.setText(TextView.java:3535)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.setText(TextView.java:3405)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.EditText.setText(EditText.java:80)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.widget.TextView.setText(TextView.java:3380)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at com.example.test2.MainActivity$RequestLogInFromServer.doInBackground(MainActivity.java:111)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-22 09:53:27.561: E/AndroidRuntime(13141):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-22 09:53:27.561: E/AndroidRuntime(13141):    ... 5 more

1 个答案:

答案 0 :(得分:2)

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.引起。您正在从非UI线程的UI上执行更改。这里至少有这一行(在AsyncTask doInBackground中):

            String text = jObj.get("masterPerosActive").toString();
            edt.setText(text);

由于您使用的是AsyncTask,为什么不在onPostExecute()方法中执行UI更改,以便您的RequestLogInServer类更改为(仅触及最后一行):

public class RequestLogInFromServer extends AsyncTask<Object, Object, String> {
    TextView txt = (TextView) findViewById(R.id.textView1);
    EditText edt = (EditText) findViewById(R.id.editText1);

    @Override
    protected Object doInBackground(Object... params) {

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
        httpPost.setHeader("Content-type", "application/json");

        try {

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            is = resEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            // strJson = null;
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); // iso-8859-1 //
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
            is.close();
            strJson = sb.toString();
        } catch (Exception e) {

        }

        try {
            if (strJson != null) {
                jObj = new JSONObject(strJson);
                String text = jObj.get("masterPerosActive").toString();
                return text;

            } else {
                jObj = null;
            }
        } catch (JSONException e) {
        }
        return null;
    }

    protected void onPostExecute(String result) {
         if(result != null) {
             edt.setText(result);
         } else {
             // show a message/label that something went wrong
         }
     }
}