如何将数据从xml解析器传递到列表视图

时间:2011-04-11 09:34:38

标签: android xml parsing listview

我有这个解析示例,它工作正常,但我无法弄清楚,如何获取列表视图中的所有数据。你能帮我找一个解决方案吗?感谢

public class XMLParsingExample extends ListActivity {

    /** Create Object For SiteList Class */
    SitesList sitesList = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** Create a new layout to display the view */
            // LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(1);

            /** Create a new textview array to display the results */
            TextView name[];

            try {

                    /** Handling XML */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    XMLReader xr = sp.getXMLReader();

                    /** Send URL to parse XML Tags */
                    URL sourceUrl = new URL("http://xxx/xxx/example.xml");

                    /** Create handler to handle XML Tags ( extends DefaultHandler ) */
                    MyXMLHandler myXMLHandler = new MyXMLHandler();
                    xr.setContentHandler(myXMLHandler);
                    xr.parse(new InputSource(sourceUrl.openStream()));

            } catch (Exception e) {
                    System.out.println("XML Pasing Excpetion = " + e);
            }

            /** Get result from MyXMLHandler SitlesList Object */
            sitesList = MyXMLHandler.sitesList;

            /** Assign textview array lenght by arraylist size */
            name = new TextView[sitesList.getName().size()];

            /** Set the result text in textview and add it to layout */
            for (int i = 0; i < sitesList.getName().size(); i++) {
                    name[i] = new TextView(this);
                    name[i].setText("Name = " + sitesList.getName().get(i));
                    layout.addView(name[i]);
            }

            /** Set the layout view to display */
            setContentView(layout);

    }
}

1 个答案:

答案 0 :(得分:0)

如果XML只是简单字符串的集合,您可以以某种方式将其解析为String[],然后只使用ArrayAdapter

如果您的数据更复杂,您可以实现自己的BaseAdapter子项并在此处执行所有绑定。它将在构造函数中接受已解析的XML,然后使用它来获取所有数据并将其绑定到视图。