从后台线程Android更新ui

时间:2013-06-16 11:35:44

标签: android android-asynctask

我需要在may异步任务中从onPostExecute方法更新UI。我正在尝试的是我正在解析一个xml并从那里获取文本..我需要从onPostExecute()为它包含文本的每个xml节点动态创建textView并将其添加到我的布局中。

当我尝试这样做时,得到了NetworkOnMainThreadException ..

我试过解决这个问题的处理程序,但没有正常工作。

请检查我的代码。

protected void onPostExecute(final InputStream stream) {
    // dismiss the dialog after getting all albums
    pDialog.dismiss();

      try {

          XmlPullParser xpp = Xml.newPullParser();
          xpp.setInput(stream, null);
            xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            xpp.next();
            int eventType = xpp.getEventType();
            System.out.println("eventType : " + eventType);

              String tagname = null;
              String type = null;
              String link = null;
              String content = null;

            while (eventType != XmlPullParser.END_DOCUMENT)
            {

                 if(eventType == XmlPullParser.START_DOCUMENT){
                    // str += "\nXML Parsing Starting...\n";
                     eventType = xpp.next();
                     continue;
                 }
                 else if(eventType == XmlPullParser.START_TAG)
                 {
                    // str +=  "\nroot tag: "+xpp.getName();
                     tagname = xpp.getName();

                     if(xpp.getName().equals("text")){
                         if(xpp.getAttributeCount()>0){
                             type = xpp.getAttributeValue(null, "type");
                            // str +=  "\nroot attr: "+type;
                         }

                     }
                     else if((xpp.getName().equals("image")) || (xpp.getName().equals("audio")) || (xpp.getName().equals("video")) ){
                         if(xpp.getAttributeCount()>0){
                             link = xpp.getAttributeValue(null, "src");
                            // str +=  "\nroot attr: "+link;
                         }
                     }
                 }

                 else if(eventType == XmlPullParser.TEXT)
                 {
                     content = xpp.getText();
                    // str += "\nvalue : "+xpp.getText();
                 }
                 else if(eventType == XmlPullParser.END_TAG)
                 {
                    // str += "\nending tag: "+xpp.getName();


                     eventType = xpp.next();
                     continue;
                 }
                 System.out.println("content : " + content);
                 System.out.println("tagname : " + tagname);

                 if(content != null ){
                 if((tagname.equals("text") || tagname.equals("preview")) ){

                     // UPDATE_TEXT =1;
                     // TextView text = new TextView(ContentView.this);
                     text = new TextView(getBaseContext());
                     text.setText(content);

                     if(type != null){
                         if(type.equals("heading1"))
                             text.setTextAppearance(ContentView.this, R.style.heading1);
                         else if(type.equals("heading2"))
                             text.setTextAppearance(ContentView.this, R.style.heading2);
                         else if(type.equals("heading3"))
                             text.setTextAppearance(ContentView.this, R.style.heading3);
                         else if(type.equals("heading4"))
                             text.setTextAppearance(ContentView.this, R.style.heading4);
                         type = null;
                     }
                     if (text != null && layout != null){
                         Log.e(getPackageName(), text.toString());

                         runOnUiThread(new Runnable() {
                             public void run() {
                                 Message message = handler.obtainMessage();
                                 message.what = 1;
                                 handler.sendMessage(message);
                                 // handler.sendEmptyMessage(1);
                                 // layout.addView(text);
                             }
                         });
                     }

                     content = null;
                 }
                 else if((tagname.equals("image"))){

                     text = new TextView(ContentView.this);
                     text.setText(content);

                     if(link != null){

                         link = null;
                     }
                     runOnUiThread(new Runnable() {
                         public void run() {
                             handler.sendEmptyMessage(1);
                    // layout.addView(text);
                         }
                     });
                     content = null;
                 }
                 }

                 eventType = xpp.next();
            }
            // str += "\n\nXML parsing Ending......";

      } catch (XmlPullParserException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
 }

在活动类中检查我的处理程序类..

protected Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case 1:
            layout.addView(text);

            break;
        case 2:
            layout.addView(text);
            break;
        }
    }
  };

仍然遇到同样的错误。

2 个答案:

答案 0 :(得分:0)

您需要数据信息和设置器的对象模型,并且可以使用它:

private ProgressDialog progressBar;

class MyTask extends AsyncTask<String, Void, String> {

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

    progressBar = new ProgressDialog(getApplicationContext());
    progressBar.setMessage("please, waiting ...");
    progressBar.setCancelable(false);
    progressBar.show();

 }

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

    try {

        // parsing xml and get data 
        // get info and set them in my model ...

    } catch (Exception e) {
        e.printStackTrace();
    }

    return params[0];
 }

 @Override
 protected void onPostExecute(String result) {
    super.onPostExecute(result);

    if (null != progressBar && progressBar.isShowing()) {
        progressBar.dismiss();
    }

    // do work in UI and set getter informations and set layout ...
   switch(select) {
   case 1:
        layout.addView(text);

        break;
    case 2:
        layout.addView(text);
        break;
    }
 }
}

答案 1 :(得分:0)

您未能发布整个AsyncTask,迫使每个人都必须猜测。

我的猜测是您在doInBackground()中建立了HTTP连接,然后将生成的InputStream传递给onPostExecute()。这不起作用,因为InputStream绑定到网络套接字。

InputStream和XML解析移至doInBackground()