开发者

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

开发者 https://www.devze.com 2023-02-19 17:53 出处:网络
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.

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: htt开发者_Go百科p://pastie.org/1708374

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

I guess it is a stupid error

thanks


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.


As a general note on how to read a NPE stacktrace:

When you get an exception stack trace, look at the Caused by line and the first line after it

Caused by: java.lang.NullPointerException
  at CentroidGenerator.nextItem2(CentroidGenerator.java:31)

A null pointer exception most often occurs when you try to invoke a method on an object and that object is null. The error message above tells you that the error occurs on line 31 of CentroidGenerator.java:

if (centroids.length == 0) {

Method invokation is of the format object.method, so you know that in this instance the object that is null is centroids.

A quick visual way to determine what's null is to just look at what's on the left of dots on the line where the exception occurs. In lines where you have multiple method calls, you don't immediately know what object is null and you may need some more exploration, but not in this instance.

To fix the problem, refer to Jon's answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消