本文介绍了Android的:如何存储在主要活动的变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网上解析XML文件后,存储在一个主要活动的一些变量的值,我有以下codeS,它运行但随后力关闭:

I want to store some values on a main activity's variable after parsing an xml file from the net, I have the following codes, it runs but then it force closes:

private class parseXMLAsync extends AsyncTask <String, String, String>{

    protected void onPreExecute(){
        super.onPreExecute();
        showDialog(PARSE_XML);
    }

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

        try{
            Engagia.this.url.openConnection();
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            ExampleHandler myExampleHandler = new ExampleHandler();
            xr.setContentHandler(myExampleHandler);
            xr.parse(new InputSource(Engagia.this.url.openStream()));

            List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

            Iterator i;
            i = parsedExampleDataSet.iterator();
            ParsedExampleDataSet dataItem;

            while(i.hasNext()){
                    dataItem = (ParsedExampleDataSet) i.next();
                    String folder = dataItem.getParentTag();


                    if( folder == "Videos"  ){

                        MainAct.this.videoNames[MainAct.this.videoCount] = dataItem.getName();

                        MainAct.this.videoCount++;
                    }

            }

        }catch(Exception e){
            Log.e(LOG_TAG, e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(String lenghtOfFile) {
        try{
            if( mProgressDialog.isShowing() ){
                dismissDialog(PARSE_XML);
            }
            //String str_contents = null;
            /*
            for(String str : MainAct.this.videoNames ){
                str_contents = str_contents + str + "\n";
            }
            */

        }catch(Exception e){
            Log.e(LOG_TAG, e.toString());
        }
        PopIt("Parsing Done", "STR CONTENTS >> " + Engagia.this.videoNames[0], "Denied");
    }
}

在logcat的说:

The logcat says:

推荐答案

要保存价值MainAct活动

To Store value in MainAct activity

首先确保MainAct活动还没有结束,而你正在使用异步任务。因为要存储的值作为MainAct的实例变量

First make sure MainAct activity is not finished while you are using Async task. because you want to store the values as instance variable of MainAct

避免赋值,像下面的

MainAct.this.videoNames[MainAct.this.videoCount] = dataItem.getName();

更好地创造在MainAct方法,该方法将设置 videoNames 的价值存在。但是,无论是使用静态方法或使用该方法的实例调用的AsyncTask类的方法。

Better create a method in MainAct which will set value of videoNames there. But call that method in AsyncTask class either using static method or using instance of that method.

谢谢迪帕克

这篇关于Android的:如何存储在主要活动的变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 21:56