从xml中提取信息但不会显示
问题描述:
没有任何内容写入TextView屏幕。从xml中提取信息但不会显示
我不知道我在做什么错在这里,但是这是我下面的代码:
<?xml version="1.0"?>
<news>
<article title="TITLE HERE" link="*.php?showtopic=118" date="DATE HERE"></article>
</news>
Java代码:
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();
}
答
您实例TextView
S和调用setContentView()
每他们...这是永远不会工作。至少你需要给出一些布局指令(即每个TextView
上调用setLayoutParams
),但我甚至不确定没有某种容器对象就可以工作。
试试这个。创建一个名为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);
}
你尝试只是设置文本,而不是html.fromHtml? – blindstuff 2010-11-29 21:09:52