views:

195

answers:

2

Hi Everyone,

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" standalone="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!

+1  A: 

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).

Thilo
Thanks Thilo, I updated my code and made it a whole lot simpler. I also identified the line of the NullPointerException...
behrk2
+3  A: 

you did not initialize the titles Vector before using it.

you need to add the following in the SearchParse constructor:

titles = new Vector();

dan
That did it, thank you for your help!
behrk2