A
A
Anton2018-01-09 09:09:53
Java
Anton, 2018-01-09 09:09:53

How to fix java.lang.NullPointerExeption?

Here is the code:

try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            final Document doc = db.parse(new File("config.xml"));

            for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    for (Node m = d.getFirstChild(); m != null; m = m.getNextSibling()) {

                        //изменить по возможности этот кусок кода.
                         String stringValue;
                        if ("variable".equals(m.getNodeName())) {
                            stringValue = m.getAttributes().getNamedItem("storiesNumber").getNodeValue().trim();
                            System.out.println(stringValue);
                            stringValue = m.getAttributes().getNamedItem("elevatorCapacity").getNodeValue().trim();
                            System.out.println(stringValue);

                        }
                    }
                }
            }

        }
        catch (Exception e) {
            System.out.println (e.getClass().getName() + " with message : " + e.getMessage());
            e.printStackTrace();
        }

Here is the output:
25
java.lang.NullPointerException with message : null
java.lang.NullPointerException

Here is the xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Lift>
    <variables>
        <variable storiesNumber = "25"/>
        <variable elevatorCapacity = "30"/>
        <variable passengerNumber = "13"/>
        <variable animationBoost = "2"/>
    </variables>

I tried to debug, but everything is correct for the variables.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-01-09
@Anton238

Look, you take a variable and ask it for attributes like storiesNumber and elevatorCapacity. Those. Your code expects the XML entry to be of the form
And in your XML the attributes storiesNumber and elevatorCapacity belong to different variables. So it turns out that you take the first variable, ask it for the storiesNumber attribute and it is there, then you ask the same variable for the elevatorCapacity attribute and it is not there, here you have NPE.

D
Denis Zagaevsky, 2018-01-09
@zagayevskiy

Look at the stack trace, where null is, and understand why it is there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question