尝试在后台解析带有AsyncTask的JSON时强制关闭

时间:2011-01-08 09:45:23

标签: android json android-asynctask

我是Android开发的新手,我正在玩json数据。我设法让解析工作。我想显示一个ProgressDialog,我读到我需要使用AsyncTask。但是出于某种原因,只要我在doInBackground()中放入相同的工作代码,我就会关闭一个力量,尽管eclipse说一切都很好。

以下是源代码:

public class HomeActivity extends Activity {


  public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {

      ProgressDialog dialog = new ProgressDialog (HomeActivity.this);


      @Override
      protected void onPreExecute() {
        dialog.setMessage("Loading...please wait");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
      }

      protected void onPostExecute() {
             dialog.dismiss();
          }

      @Override
      protected Void doInBackground(Void... params) {         
            try {
                URL json = new URL("http://www.corps-marchia.de/jsontest.php");
                URLConnection tc = json.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

                String line;
                while ((line = in.readLine()) != null) {
                    JSONArray ja = new JSONArray(line);
                    JSONObject jo = (JSONObject) ja.get(0);
                    TextView txtView = (TextView)findViewById(R.id.TextView01);
                    txtView.setText(jo.getString("text"));
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

       return null;
       }
     }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new BackgroundAsyncTask().execute();
    }

}

以下是错误日志:

01-08 12:33:48.225: ERROR/AndroidRuntime(815): FATAL EXCEPTION: AsyncTask #1
01-08 12:33:48.225: ERROR/AndroidRuntime(815): java.lang.RuntimeException: An error occured while executing doInBackground()
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.lang.Thread.run(Thread.java:1019)
01-08 12:33:48.225: ERROR/AndroidRuntime(815): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.ViewRoot.requestLayout(ViewRoot.java:629)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.View.requestLayout(View.java:8267)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.View.requestLayout(View.java:8267)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.View.requestLayout(View.java:8267)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.View.requestLayout(View.java:8267)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.view.View.requestLayout(View.java:8267)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.widget.TextView.checkForRelayout(TextView.java:5521)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.widget.TextView.setText(TextView.java:2724)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.widget.TextView.setText(TextView.java:2592)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.widget.TextView.setText(TextView.java:2567)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.doInBackground(HomeActivity.java:52)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.doInBackground(HomeActivity.java:1)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-08 12:33:48.225: ERROR/AndroidRuntime(815):     ... 4 more
01-08 12:33:51.605: ERROR/WindowManager(815): Activity net.ajzele.demo.andy1.HomeActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051d0c0 that was originally added here
01-08 12:33:51.605: ERROR/WindowManager(815): android.view.WindowLeaked: Activity net.ajzele.demo.andy1.HomeActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051d0c0 that was originally added here
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.view.ViewRoot.<init>(ViewRoot.java:258)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.Dialog.show(Dialog.java:241)
01-08 12:33:51.605: ERROR/WindowManager(815):     at net.ajzele.demo.andy1.HomeActivity$BackgroundAsyncTask.onPreExecute(HomeActivity.java:33)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.os.AsyncTask.execute(AsyncTask.java:391)
01-08 12:33:51.605: ERROR/WindowManager(815):     at net.ajzele.demo.andy1.HomeActivity.onCreate(HomeActivity.java:72)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.os.Looper.loop(Looper.java:123)
01-08 12:33:51.605: ERROR/WindowManager(815):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-08 12:33:51.605: ERROR/WindowManager(815):     at java.lang.reflect.Method.invokeNative(Native Method)
01-08 12:33:51.605: ERROR/WindowManager(815):     at java.lang.reflect.Method.invoke(Method.java:507)
01-08 12:33:51.605: ERROR/WindowManager(815):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-08 12:33:51.605: ERROR/WindowManager(815):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-08 12:33:51.605: ERROR/WindowManager(815):     at dalvik.system.NativeStart.main(Native Method)

任何提示?我希望你能帮助我搜索网络并没有找到任何有效的解决方案......提前致谢

2 个答案:

答案 0 :(得分:2)

不允许您从非UI /主线程更新GUI元素

txtView.setText(jo.getString("text"));

Handling Expensive Operations in the UI Thread

或使用

onPostExecute

答案 1 :(得分:2)

检查docs for AsyncTask。您无法直接在doInBackground内操纵用户界面。要进行UI更新,您需要致电publishProgress。您还需要更改AsyncTask的签名以传递String。所以像这样:

public class BackgroundAsyncTask extends AsyncTask<Void, String, Void> {
    TextView txtView = (TextView)findViewById(R.id.TextView01);
    ...
    protected void onProgressUpdate(String... message) {
        txtView.setText(message[0]);
    }
    ...
    @Override
    protected Void doInBackground(Void... params) {
         try {
             URL json = new URL("http://www.corps-marchia.de/jsontest.php");
             URLConnection tc = json.openConnection();
             BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

             String line;
             while ((line = in.readLine()) != null) {
                 JSONArray ja = new JSONArray(line);
                 JSONObject jo = (JSONObject) ja.get(0);
                 publishProgress(jo.getString("text"));
             }
         } catch (MalformedURLException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } catch (JSONException e) {
             e.printStackTrace();
         }

    return null;
    }