Search code examples
javaapache-commons-digester

Java, Digester: stuck on this java.lang.NullPointerException


I'm parsing a XML file with Commons Digester and I don't understand what's wrong in my code: I'm stuck with this java.lang.NullPointerException.

THis is the code: http://pastie.org/1708374

and this is the exception: http://pastie.org/1708371

I guess it is a stupid error

thanks


Solution

  • Well, this is the problem:

    if (centroids.length == 0)
    

    You're never assigning a value to centroids as far as I can see, so it will always be null. Then when you try to dereference it in the line above, it will throw NullPointerException.

    The first that the next line of code tried to use centroids[0] suggests that you don't really understand Java arrays. Perhaps you really wanted a List of some description?

    I would also strongly suggest that instead of a Map<String, String> which always has the same five keys, you create a type (e.g. Centroid) which has the properties title, description, tags, time, and event. Then you can just make centroids a List<Centroid>:

    List<Centroid> centroids = new ArrayList<Centroid>();
    

    then when you get some data...

    Centroid centroid = new Centroid(...);
    centroids.add(centroid);
    

    Oh, and you're also currently using == to compare strings... don't do that: use equals, as otherwise you'll be comparing string references.