从xml中提取信息但不会显示

时间:2010-11-29 21:04:13

标签: android xml

没有任何内容写入TextView屏幕。

我不确定我在这里做错了什么,但这是我的以下代码:

<?xml version="1.0"?> 
 <news> 
  <article title="TITLE HERE" link="*.php?showtopic=118" date="DATE HERE"></article> 
 </news>

JAVA CODE:

try {
    //open an URL connection make GET to the server and
    URL url = new URL("http://.../m_news.xml");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    InputStream is = conn.getInputStream();

    //DocumentBuilderFactory, DocumentBuilder are used for
    //xml parsing
    DocumentBuilderFactory dbf = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    //using db (Document Builder) parse xml data and assign
    //it to Element
    Document document = db.parse(is);
    Element element = document.getDocumentElement();

    NodeList nodeList = element.getElementsByTagName("news");
    NodeList nodeList2 = element.getElementsByTagName("article");

        if (nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList2.getLength(); i++) {
                Element entry = (Element) nodeList.item(0); 

                Element _rowE = (Element) entry.getElementsByTagName("article").item(i);  
                Node _rowTITLE = _rowE.getAttributes().getNamedItem("title");
                Node _rowLINK = _rowE.getAttributes().getNamedItem("link");

                TextView textview = new TextView(this);
                textview.setMovementMethod(LinkMovementMethod.getInstance());
                String text = "<a href='"+_rowLINK.getNodeValue()+"'>"+_rowTITLE.getNodeValue()+"</a>";
                textview.setText(Html.fromHtml(text));
                setContentView(textview);
            }
        }    
    }
} catch (Exception e) {
    e.printStackTrace();
}

1 个答案:

答案 0 :(得分:1)

您正在实例化TextView并为每个人调用setContentView() ...这永远不会起作用。至少你需要给出一些布局指令(即在每个setLayoutParams上调用TextView),但我甚至不确定在没有某种容器对象的情况下它会工作。

试试这个。创建一个名为news.xml的简单布局,其中包含:

<LinearLayout
    android:id="@+id/newsItems"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
/>

然后更改您的代码以包含以下内容:

setContentView(R.layout.news);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.newsItems);
...
for (int i = 0; i < nodeList2.getLength(); i++) {
    ...
    TextView textview = new TextView(this);
    textview.setLayoutParams(new LinearLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT));
    ...
    textview.setText(Html.fromHtml(text));
    linearLayout.addView(textview);
}