我正在开发一个应用程序,该应用程序在android中显示书籍列表。其中,我从服务器检索XML文件,并将内容解析为相应的TextViews。
我的XML文件:
<bib>
<book year="1988">
<title>Book Title</title>
<author>
<last>Jones</last>
<first>Ryan</first>
</author>
</book>
<book year="2001">
<title>Book Title 2</title>
<author>
<last>Ryans</last>
<first>Jack</first>
</author>
</book>
我使用ViewModel来使用NodeList将XML解析到我的应用程序上。
ViewModel.java:
try {
String bFeed = getApplication().getString(R.string.feed);
URL url = new URL(bFeed);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the book feed.
Document dom = db.parse(in);
// Returns the root element.
Element docEle = dom.getDocumentElement();
books.clear();
NodeList nl = docEle.getElementsByTagName("book");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (isCancelled()) {
return books;
}
Element bookElement = (Element) nl.item(i);
Element title = (Element) bookElement
.getElementsByTagName("title").item(0);
Element author = (Element) bookElement
.getElementsByTagName("author").item(0);
String bookTitle = title.getFirstChild().getNodeValue();
String bookYear = ((Element) bookElement).getAttribute("year");
// Error occurs
String bookAuthor = author.getFirstChild().getNodeValue();
final Book bookObject = new Book(bookTitle, bookYear, bookAuthor);
books.add(bookObject);
}
}
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} catch (ParserConfigurationException e) {
Log.e(TAG, "Parser Configuration Exception", e);
} catch (SAXException e) {
Log.e(TAG, "SAX Exception", e);
}
return books;
}
我在运行时收到这个错误:
引起原因:java.lang.NullPointerException:试图在null对象引用上调用接口方法"org.w3c.dom.Element.getFirstChild((">
book.java:
public class Book {
private String year;
private String title;
private String author;
public String getYear() { return year; }
public String getTitle() {
return title;
}
public String getAuthor() { return author; }
public Book(String year, String title, String author) {
this.year = year;
this.title = title;
this.author = author;
}
我希望能够获得作者的子节点。如果有人能就我做错了什么提供任何建议,我将不胜感激?
感谢
您收到的错误非常明显:
java.lang.NullPointerException:尝试在null对象引用上调用接口方法"org.w3c.dom.Element.getFirstChild((">
意思是,您正试图在一个为null的对象上调用getFirstChildMethod。
我会在下面的行中检查:
String bookTitle = title.getFirstChild().getNodeValue();
标题确实有价值。
在没有看到您正在解析的实际XML的情况下,以下几行是罪魁祸首:
Element bookElement = (Element) nl.item(i);
Element title = (Element) bookElement.getElementsByTagName("title").item(0);