AsyncTask显示进度条

时间:2012-01-20 10:57:20

标签: android android-asynctask android-progressbar

我对android很新。我有两个活动A,B。活动A从服务器解析数据并遍历级别。并通过意图调用活动B.活动B需要一些时间来显示数据,所以我试图显示进度条。这是我的代码。

 public class Display extends Activity  {

        ProgressDialog dialog;


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

            new asynctask().execute();


        }

        class asynctask extends AsyncTask<Context,Void,Void>{
            Survey[] surveyque=null;
    // i hace created seperated class forsurvey that has info about data
            String list[];  


            private ProgressDialog Dialog;
            @Override
            protected void onPreExecute()
            {
                Dialog=ProgressDialog.show(Display.this, "Parsing Data", "Please wait..........");


            }
            @Override
            protected void onPostExecute(Void unused)    
            {
                try
                {
                    if(Dialog.isShowing())
                    {
                        Dialog.dismiss();
                    }
                    Intent intent=getIntent();

                }
                catch(Exception e)
                {
    Log.d("Onsitev4", "error");
                }
            }

            @Override
            protected Void doInBackground(Context... params) {
                try {

                    LinearLayout layout1 = (LinearLayout) findViewById(R.id.linearLayout1);

    //getting exception here. I dont understant why
    // I have declared layout params and displaying activities in another class 

                    ButtonView c = new ButtonView();                
                    c.layout=layout1;
                    c.context =getBaseContext();


                    DbCoreSqlSurveys surveys=new DbCoreSqlSurveys(getBaseContext());
                    Document doc =surveys.getSurveySet();
                    surveyquestions= GetSurveyLevels(doc,c );


                } catch (TransformerFactoryConfigurationError e) {
                    e.printStackTrace();
                }
                return null;
            } 

        }

        public SurveyObject[] GetSurveyLevels(Document doc, ButtonView c) {
            NodeList nlQuestions = doc.getElementsByTagName("Survey");
            SurveyObject[] allsurveys = new SurveyObject[nlQuestions.getLength()];


            for (int i = 0; i < nlQuestions.getLength(); i++){

                Node survey =  nlQuestions.item(i);
                String f =survey.getNodeName();
                Log.d("OnsiteV4", "survey " + f);

                NodeList surveyChildNodes = survey.getChildNodes();
                SurveyObject s=new SurveyObject();

                for (int j = 0; j < surveyChildNodes.getLength(); j++){

                    Node surveyChild =  surveyChildNodes.item(j);               
                    String h =surveyChild.getNodeName();
                    Log.d("OnsiteV4", "survey child node = " + h);

                    if (h !="#text"){
                        Surveys t = Surveys.valueOf(h); 

                        switch(t){
                        case KeySurvey:
                            s.KeySurvey=surveyChild.getTextContent();
                            displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
                            break;
                        case SurveyDescription:
                            s.SurveyDescription=surveyChild.getTextContent();
                            displaySurveyLink(s.SurveyDescription,"",c,0,s.SurveyDescription,"","","","");
                            break;
                        case SurveyUserCode:
                            s.SurveyUserCode=surveyChild.getTextContent();
                            break;
                        case Level1:
                            if(surveyChild.hasChildNodes()){
                                s.Level1=   processLevel1Nodes(surveyChild,c,s.SurveyDescription);
                            }
                            break;
                        default:
                            break;
                        }
                    }

                    allsurveys[i]=s;
                }
            }

            return allsurveys;
        }

    // methods iterating through levels that is not showed

        private  void displaySurveyLink(final String description, String tag, ButtonView c, int indentation, final String surveyDescription, final String level1description, final String level2description, final String level3description, final String level4description)
        {
            if (description == null || tag == null){
                return;
            }
            final TextView tv = c.addButton(description,tag,indentation);


            tv.setOnClickListener(new OnClickListener(){
                public void onClick(View v) {

                    final Intent intent = new Intent();
                    intent.setClass(v.getContext(),ActivityB.class);
                    intent.putExtra("KeyLevel",tv.getTag().toString()); 

                    intent.putExtra("SurveyDescription",surveyDescription);
                    intent.putExtra("level1description",level1description);
                    intent.putExtra("level2description",level2description);
                    intent.putExtra("level3description",level3description);
                    intent.putExtra("level4description",level4description);
                    intent.putExtra("Description",description);

                    if (tv.getTag() != null){
                        if (tv.getTag().toString() != ""){
                            startActivity(intent);
                        }


                    }
                }


            });
        }
    }  

我在doinbackground中遇到异常。我很迷惑 。请帮帮我..

2 个答案:

答案 0 :(得分:0)

当你在asyc任务的doinbackgound做UI内容时,你的代码应该抛出异常。请从dobackgound方法中删除所有与UI相关的工作。

答案 1 :(得分:0)

您正在获取异常,因为您正在访问非UI线程上的UI元素。应用程序创建的主要线程是UI线程,这就是创建所有可视元素的位置,因此也是您应该访问它们的唯一线程。

要正确使用AsyncTask,您可以在doInBackground中运行长时间运行的操作,并使用onPreExecuteonPostExecuteonProgressUpdated来处理用户界面(显示/隐藏进度对话框,更新视图等)。每当我使用AsyncTask并且我想显示进度时,我重写onProgressUpdated,给它参数类型为Integer,我从doInBackground调用publishProgress。这需要将基类签名从AsyncTask<Context,Void,Void>更改为AsyncTask<Context,Integer,Void>。您也可以使用其他对象类型...例如,如果要显示完成任务的百分比,我只使用Integer作为示例。