java NullPointerException when parsing XML
I keep receiving a java.lang.NullPointerException while trying to store the values into my Vector. Here is the XML document:
<?xml version="1.0" stan开发者_如何学编程dalone="yes"?>
<autocomplete>
<autocomplete_item>
<title short="Forrest Gump"></title>
</autocomplete_item>
<autocomplete_item>
<title short="Forrest Landis"></title>
</autocomplete_item>
<autocomplete_item>
<title short="Finding Forrester"></title>
</autocomplete_item>
<autocomplete_item>
<title short="Menotti: The Medium: Maureen Forrester"></title>
</autocomplete_item>
</autocomplete>
And here is my updated code:
import java.util.Vector;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class SearchParse extends DefaultHandler {
Vector titles;
public SearchParse() {
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String value = attributes.getValue(i);
titles.addElement(value);
}
}
public Vector getTitles() {
return titles;
}
}
The NullPointerException is occuring at the following line:
titles.addElement(value);
Does anyone know why this is? Thanks!
you did not initialize the titles Vector before using it.
you need to add the following in the SearchParse constructor:
titles = new Vector();
We need the stack trace, but this kind of coding pattern is going to get you into trouble
DocumentBuilder docBuilder = null;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
docBuilder.isValidating();
Do not catch any of these exceptions and then continue using the variable which can only be null. If you have no way to handle the exception, you must not catch them (or catch and rethrow them).
精彩评论