在我的应用我解析XML,一块结构做题:Android的 - XML解析 - 工作的仿真器,但不是在设备
<answers>
<answer value="A">A</answer>
<answer value="B">B</answer>
<answer value="C">C</answer>
</answers>
我与XML DOM解析它:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
那伟大工程,并根据答案的项目我创建一个单选按钮这样的:
NodeList answers = doc.getElementsByTagName("answers").item(0).getChildNodes();
int j = 0;
RadioGroup group = new RadioGroup(this);
RadioButton button1 = new RadioButton(this);
button1.setId((i+1)*100+(j++));
button1.setText(answers.item(1).getChildNodes().item(0).getNodeValue());
button1.setTextColor(Color.BLACK);
RadioButton button2 = new RadioButton(this);
button2.setId((i+1)*100+(j++));
button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue());
button2.setTextColor(Color.BLACK);
RadioButton button3 = new RadioButton(this);
button3.setId((i+1)*100+(j));
button3.setText(answers.item(3).getChildNodes().item(0).getNodeValue());
button3.setTextColor(Color.BLACK);
这段代码工作PE我的HTC Desire在Android 2.1u1上运行(所以SDK v.8)
但是在设备中,我在这条线上得到了错误button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue());
猜测没有这个模拟器的SDK v.7(Android 2.0)在回答.item(2)
- 但它必须是...我调试仿真器中运行此代码,并发现answers.item(0)
是包含XML节点的“答案”的名称TextNode
...
但它是真实的我有点困惑,解析这个XML时一切都搞乱了,因为我仍然需要计算我在什么时候调用哪个索引以及何时调用哪个元素(节点)......但是我仍然发现这个实现比使用SAX
简单得多。 ..
是不是有什么simillar到SimpleXml
PHP中的Java????
无论如何,我的主要问题是:它怎么可能是应用程序在模拟器中完美工作,而在设备上它会抛出NullPointerException
在我尝试设置button2文本的行?
非常感谢您的帮助!
呵呵,当我直接在devicem上输出setText()的值,'button1.setText(answers.item(1).getChildNodes()。item(0)。getNodeValue());'在没有错误的情况下处理,并且在下一个项目'button2.setText(answers.item(2).getChildNodes()。item(0).getNodeValue());'时抛出错误。因此,我完全不理解它... – shadyyx 2011-05-05 17:42:43
我的建议:停止使用文档构建器在Android中解析XML,而是使用简单库(http://simple.sourceforge.net/),这里是一篇博文(http://massaioli.homelinux.com/wordpress/2011/04/21/simple-xml-in-android-1-5-and-up/) – 2011-05-06 00:52:00
@RobertMassaioli:嗯,我看着它,它看起来不错,但仍然不是很简单 - 你必须在XML中为每个“对象”编写和定义一个类(所以对于每个TAG) - 简化的地方在哪里?是的,也许当解析XML时,它更简单,但是你必须生成更多的代码两次...但是 - 当还剩一段时间时,我会试一试... – shadyyx 2011-05-06 11:20:23