0

我正在编写一个简单的 Android 应用程序来使用 XPath 在 ListView 中显示 XML 内容。我的代码在下面给出。它正在捕获空异常。请帮帮我:(我试过谷歌和不同的教程,但似乎没有一个能解决我的问题:(

public class MainActivity extends ListActivity {

ArrayList<String> mPeople = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        parseData();
    } catch(Exception ex) {
        Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        System.out.println(ex.getMessage() +"==============");

    }

    // pass adapter w/ data queried through XPath to ListView
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
    setListAdapter(adapter);
}

private void parseData() throws Exception {    
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(new URL("http://www.w3schools.com/xpath/books.xml").openStream());
// query XPath instance, this is the parser
XPath xpath = XPathFactory.newInstance().newXPath();
// specify the xpath expression
// String expression = " /bookstore/book/title ";

XPathExpression e = xpath.compile("/bookstore/book/title");

// list of nodes queried
NodeList nodes = (NodeList)e.evaluate(doc, XPathConstants.NODESET);

Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
// if node found
if(nodes != null && nodes.getLength() > 0) {
  mPeople.clear();
  int len = nodes.getLength();
  for(int i = 0; i < len; ++i) {
      // query value
      Node node = nodes.item(i);
      mPeople.add(node.getTextContent());
  }
}
}
}

我得到的输出是一个包含异常的 Toast:null。我想openStream()db.parse()回归null。如果有人找到解决方案,请告诉我,将不胜感激。谢谢。

编辑:这是 Logcat

06-01 10:25:42.586: I/System.out(1401): null==============
06-01 10:25:45.721: I/Choreographer(1401): Skipped 210 frames!  The application may be doing too much work on its main thread.
06-01 10:25:47.226: I/Choreographer(1401): Skipped 1768 frames!  The application may be doing too much work on its main thread.
06-01 10:25:47.467: D/gralloc_goldfish(1401): Emulator without GPU emulation detected.
4

1 回答 1

0

尝试使用 asynctask 执行 parseData() 功能并从活动 oncreate 调用 asynctask.execute。它可能会解决您的问题。你得到了这个错误- 应用程序可能在其主线程上做太多的工作只是因为你在主线程上进行网络调用,因为它可能需要超过 6 秒的时间,因为应用程序可能会被操作系统视为“ANR”。

于 2013-06-01T11:18:46.347 回答