1

我有两个文件 XMLParser 从 URL 和 Activity 解析 XML。似乎getter方法不起作用。我可以在 XMLParser 文件中输出 arrayList 的值。但不在活动文件中。

public class XMLParser extends AsyncTask<Void, Void, ArrayList<Object>> {

    ArrayList<String> groupItem = new ArrayList<String>();
    ArrayList<Object> childItem = new ArrayList<Object>();
    ArrayList<String> child = new ArrayList<String>();


    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            System.out.println("authType is " + authType);
            System.out.println("cert issuers");
            for (int i = 0; i < certs.length; i++) {
                System.out.println("\t"
                        + certs[i].getIssuerX500Principal().getName());
                System.out.println("\t" + certs[i].getIssuerDN().getName());
            }
        }
    } };

    @Override
    protected ArrayList<Object> doInBackground(Void... params) {

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            URL url = new URL();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("Device");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element deviceElement = (Element) nodeList.item(i);
                groupItem.add(deviceElement.getAttribute("serial"));
                child = new ArrayList<String>();
                child.add(deviceElement.getAttribute("model"));
                child.add(deviceElement.getAttribute("asset"));
                child.add(deviceElement.getAttribute("location"));
                child.add(deviceElement.getAttribute("lastConnected"));
                childItem.add(child);
            }
;
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        return childItem;
    }

    protected void onPostExecute() {
        // here you will get the result
    }

    public ArrayList<String> getGroupItem() {

        return groupItem;
    }

    public ArrayList<Object> getChildItem() {
        return childItem;
    }

这是活动文件:

public class DevicesActivity extends ExpandableListActivity implements
OnChildClickListener  {
    ArrayList<String> groupItem = new ArrayList<String>();
    ArrayList<Object> childItem = new ArrayList<Object>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /** Create a new layout to display the view */
         //setContentView(R.layout.activity_devices);

        //ExpandableListView expandbleLis = getExpandableListView();
        //expandbleLis.setDividerHeight(2);
        //expandbleLis.setGroupIndicator(null);
        //expandbleLis.setClickable(true);
        startXMLParser();

        System.out.println("size in Device "+groupItem.size());
        System.out.println("size in Device "+childItem.size());



    }
    private void startXMLParser() {
        XMLParser XMLTask = new XMLParser();
        XMLTask.execute(null,null,null);
        groupItem=XMLTask.getGroupItem();
        childItem=XMLTask.getChildItem();
}

获取数组列表:

public void getArrayList(ArrayList<DataInterface> lst) {
        finalList=lst;

    }
4

2 回答 2

1

由于AyncTask是异步的,因此无法保证当您调用方法来检索数据时结果会存在,事实上,它可能不会存在。在尝试访问这些变量之前,您需要确保任务已完成。

一种解决方案是将这些数据传递到Activityin onPostExecute()。如果这个类是一个内部类,Activity那么你可以拥有成员变量并将它们分配给onPostExecute()其他AsyncTask方法。

此外,您应该parameter在声明中包含该类型,onPostExecute()否则它将不会收到结果。你应该添加@Override注释

@Override
protected void onPostExecute(ArrayList<Object> result) {
    // here you will get the result
}

在 AsyncTask 创建一个构造函数来接收Context

Activity mAct;
public calss MyTask extends AsyncTask<...>  // you know what to add here
{
    public MyTask(Activity act)
    {
         mAct = act;
    }

然后使用mContextinonPostExecute()调用你的Activity函数

创建任务时

MyTask task = new MyTask(this);  // pass context to constructor
taske.execute(// add params);

public void onPostExecute(ArrayList<Object> result){
    mAct.yourMethod(result);
于 2013-05-31T14:20:11.543 回答
0

下面的例子给你的想法

@Override
    protected void onPostExecute(ArrayList<Object> result) {
        // here you will get the result               ||    This Must Be Same
    }                                                 \/ 
    protected                          ArrayList<Object> doInBackground(String... params)

doInBackground 的返回类型和 PostExecute 的参数必须相同

于 2013-05-31T14:31:55.973 回答