Results 1 to 14 of 14
  1. #1
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Question NullPointerException

    Can someone please explain why I keep getting a null pointer exception in the same place when I'm trying to parse a file (about 1/4 of the way through)? The file is about a 1.5 MB

    Java Code:
    import java.io.File;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException; 
    
    public class ReadAndPrintGetitems{
    
       public static void main (String argv []){
        try {
    
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                 
        
    
                Document doc = docBuilder.parse (new File("GetItems.xml"));
    
                // normalize text representation
                doc.getDocumentElement ().normalize ();
                System.out.println ("Root element of the doc is " + 
                     doc.getDocumentElement().getNodeName());
    
    
                NodeList listOfItems = doc.getElementsByTagName("item");
                int totalItems = listOfItems.getLength();
                System.out.println("Total no of <item> tags found : " + totalItems);
    
                for(int s=1; s<listOfItems.getLength() ; s++){
    
    
                    Node firstItemNode = listOfItems.item(s);
                    if(firstItemNode.getNodeType() == Node.ELEMENT_NODE){
    
    
                        Element firstItemElement = (Element)firstItemNode;
    
                        //-------
                        NodeList firstIdList = firstItemElement.getElementsByTagName("id");
                        Element firstIdElement = (Element)firstIdList.item(0);
    
                        NodeList textIdList = firstIdElement.getChildNodes();
                        System.out.println("id   : " + 
                               ((Node)textIdList.item(0)).getNodeValue().trim());
    
                        //-------
                        NodeList nameList = firstItemElement.getElementsByTagName("name");
                        Element nameElement = (Element) nameList.item(0);
    
                        NodeList textLNList = nameElement.getChildNodes();
                        System.out.println("name : " + 
                               ((Node)textLNList.item(0)).getNodeValue().trim());
    
                        //----
                        NodeList typeList = firstItemElement.getElementsByTagName("type");
                        Element typeElement = (Element) typeList.item(0);
    
                        NodeList textAgeList = typeElement.getChildNodes();
                        System.out.println("type : " + 
                               ((Node)textAgeList.item(0)).getNodeValue().trim());
    
                        //------
    
    
                    }//end of if clause
    
    
                }//end of for loop with s var
    
    
            }catch (SAXParseException err) {
            System.out.println ("** Parsing error" + ", line " 
                 + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());
    
            }catch (SAXException e) {
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();
    
            }catch (Throwable t) {
            t.printStackTrace ();
            }
            //System.exit (0);
    
        }//end of main
    
    }

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

  3. #3
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    5

    Default

    its possible the xml document is missing a tag that the code is expecting to always have there, for one of the nodes way down in the document.

    For example, instead of doing :

    NodeList nameList = firstItemElement.getElementsByTagName("name");
    Element nameElement = (Element) nameList.item(0);
    If there was for some reason no "name" tag in the XML, the nameList would be null, and then we get a NPE on namelist.item(0). So instead, do

    Java Code:
    NodeList nameList = firstItemElement.getElementsByTagName("name");
    Element nameElement = null;
    if (nameList != null) {
      nameElement = (Element) nameList.item(0);
      // maybe something here that uses nameElement, 
    }
    else {
      // if this really can not ever be null, generate your own meaningful error message here.
    }
    where you would want to do this for all the other places of this pattern..

    And again, for places like this,
    System.out.println("type : " +
    ((Node)textAgeList.item(0)).getNodeValue().trim()) ;
    instead, do something like

    Java Code:
    String value = null;
    
    Node aNode = null;
    if (textAgeList != null) {
      aNode = (Node)textAgeList.item(0);
      if (aNode != null) {
        value = aNode.getNodeValue();
        if (value != null) {
          value = value.trim();
        }
      }
    }
    System.out.println("type : " + value);

  4. #4
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Default

    java.lang.NullPointerException
    at parserTest.main(parserTest.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.dynamicjava.symbol.JavaClass$JavaMetho d.evaluate(JavaClass.java:326)
    at edu.rice.cs.dynamicjava.interpreter.ExpressionEval uator.handleMethodCall(ExpressionEvaluator.java:92 )
    at edu.rice.cs.dynamicjava.interpreter.ExpressionEval uator.visit(ExpressionEvaluator.java:84)
    at koala.dynamicjava.tree.StaticMethodCall.acceptVisi tor(StaticMethodCall.java:105)
    at edu.rice.cs.dynamicjava.interpreter.ExpressionEval uator.value(ExpressionEvaluator.java:38)
    at edu.rice.cs.dynamicjava.interpreter.ExpressionEval uator.value(ExpressionEvaluator.java:37)
    at edu.rice.cs.dynamicjava.interpreter.StatementEvalu ator.visit(StatementEvaluator.java:106)
    at edu.rice.cs.dynamicjava.interpreter.StatementEvalu ator.visit(StatementEvaluator.java:29)
    at koala.dynamicjava.tree.ExpressionStatement.acceptV isitor(ExpressionStatement.java:101)
    at edu.rice.cs.dynamicjava.interpreter.Interpreter.ev aluate(Interpreter.java:86)
    at edu.rice.cs.dynamicjava.interpreter.Interpreter.in terpret(Interpreter.java:47)
    at edu.rice.cs.drjava.model.repl.newjvm.InterpreterJV M.interpret(InterpreterJVM.java:205)
    at edu.rice.cs.drjava.model.repl.newjvm.InterpreterJV M.interpret(InterpreterJVM.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
    at sun.rmi.transport.Transport$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages( Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandl er.run0(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandl er.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run Task(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (Unknown Source)
    at java.lang.Thread.run(Unknown Source)

  5. #5
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    What you have on line 45 of the at parserTest.java file?

    at parserTest.main(parserTest.java:45)

  6. #6
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Default

    Here is what is on line 45 of parserTest.java

    Java Code:
    NodeList textIdList = firstIdElement.getChildNodes();

  7. #7
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Fine, you are retrieving items here. Somehow items are not in. Did you check the content before retrieve.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,925
    Rep Power
    19

    Default

    Java Code:
                        NodeList firstIdList = firstItemElement.getElementsByTagName("id");
                        Element firstIdElement = (Element)firstIdList.item(0);
    Based on that code, there are no elements inside firstItemElement that have a name of "id", so item(0) is returning null. Are you sure that all <item>s have a sub element that is <id>?

  9. #9
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Default

    Thanks for the reply. Yes you are right not all <item> have a sub element that is <id>. This is what I see printed out:

    Java Code:
    ..........
    id   : 302
    name : Cisco RNG200
    type  : 6
    id   : 303
    name : Cable
    type  : 7
    id   : 322
    name : WeatherBug Forecasts
    type  : 7
    java.lang.NullPointerException
    	at ReadAndPrintGetitems.main(ReadAndPrintGetitems.java:42)
    Here is section where it stops parsing in the XML
    Java Code:
    <item>
    <id>322</id>
    <name>WeatherBug Forecasts</name>
    <type>7</type>
    <itemdata><large_image>devices_sm/contactsingle_humiditysensor_open.gif</large_image><small_image>devices_sm/contactsingle_humiditysensor_open.gif</small_image><config_data_file>weatherbug.c4i</config_data_file><tag>c8969fc5_a55a_4bf5_9d13_1e842be90ea4</tag></itemdata>
    <state>&lt;lua_gen_persisting&gt;&lt;properties&gt;&lt;property&gt;&lt;name&gt;Location Code&lt;/name&gt;&lt;value&gt;77040&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Location Type&lt;/name&gt;&lt;value&gt;US (Zip Code)&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Units Type&lt;/name&gt;&lt;value&gt;US Units&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Alert Font Size&lt;/name&gt;&lt;value&gt;Medium&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Current Font Size&lt;/name&gt;&lt;value&gt;Medium&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Forecast Font Size&lt;/name&gt;&lt;value&gt;Medium&lt;/value&gt;&lt;/property&gt;&lt;property&gt;&lt;name&gt;Debug Mode&lt;/name&gt;&lt;value&gt;Off&lt;/value&gt;&lt;/property&gt;&lt;/properties&gt;&lt;LuaPersistentData&gt;PersistData = {}
    &lt;/LuaPersistentData&gt;&lt;/lua_gen_persisting&gt;</state><devicedata>
        <copyright>Copyright 2004-2008 Control4 Corporation.  All rights reserved.</copyright>
        <manufacturer>weatherbug</manufacturer>
        <model>WeatherBug Forecasts</model>
        <creator>RyanE</creator>
        <name>WeatherBug Forecasts</name>
        <small>devices_sm/contactsingle_humiditysensor_open.gif</small>
        <large>devices_sm/contactsingle_humiditysensor_open.gif</large>
        <control>lua_gen</control>
        <proxy>weatherbug</proxy>
        <driver>DriverWorks</driver>
        <states/>
        <config>
            <documentation>This is a driver that retrieves weather data from connecting to the WeatherBug API.\n\nYou must first set the Address of this driver (in 'Connections -- Network') to the Hostname.\n\nFor API information, see: NOTE: This driver will not capture more than one active Weather Alert, and should not be used as life-safety alerting system...\n\nTo get a list of Zip or City codes, use the 'Lua' tab, and enter SearchLocations(), and pass in a name or zip code to search for.  For example, to verify a valid zipcode for Draper, UT, enter: SearchLocations("84020").  To Search for a city that sounds like 'Paris', enter: SearchLocations("paris")\n\nThe Font Size Properties do not apply to the Mini-Touch, which only has a single font size.</documentation>
            <properties>
    <property>
                    <name>Location Code</name>
                    <type>STRING</type>
                    <default/>
                    <readonly>false</readonly>
                </property>
                <property>
                    <name>Location Type</name>
                    <type>LIST</type>
                    <items>
                        <item>US (Zip Code)</item>
                        <item>Foreign (City Code)</item>
                    </items>
                    <default>US (Zip Code)</default>
                    <readonly>false</readonly>
                </property>
                <property>
                    <name>Units Type</name>
                    <type>LIST</type>
                    <items>
                        <item>US Units</item>
                        <item>Metric Units</item>
                    </items>
                    <default>US Units</default>
                    <readonly>false</readonly>
                </property>
                <property>
                    <name>Alert Font Size</name>
                    <type>LIST</type>
                    <items>
                        <item>XX-Small</item>
                        <item>X-Small</item>
                        <item>Small</item>
                        <item>Medium</item>
                        <item>Large</item>
                        <item>X-Large</item>
                        <item>XX-Large</item>
                    </items>
                    <default>Medium</default>
                    <readonly>false</readonly>
                </property>
                <property>
                    <name>Current Font Size</name>
                    <type>LIST</type>
                    <items>
                        <item>XX-Small</item>
                        <item>X-Small</item>
                        <item>Small</item>
                        <item>Medium</item>
                        <item>Large</item>
                        <item>X-Large</item>
                        <item>XX-Large</item>
                    </items>
                    <default>Medium</default>
                    <readonly>false</readonly>
                </property>
                <property>
                    <name>Forecast Font Size</name>
                    <type>LIST</type>
                    <items>
                        <item>XX-Small</item>
                        <item>X-Small</item>
                        <item>Small</item>
                        <item>Medium</item>
                        <item>Large</item>
                        <item>X-Large</item>
                        <item>XX-Large</item>
                    </items>
    ........
    How do I go about fixing this? I tried what travishein but I still no luck.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I tried what travishein but I still no luck.
    This doesn't tell us much, and in fact tells us nothing about what specifically you've tried and what problems have occurred from it.

  11. #11
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Default

    Here is what I tried.

    Java Code:
    //-------
                        NodeList IdList = firstItemElement.getElementsByTagName("id");
                        Element IdElement = null;
                        if (IdList != null) {
                        IdElement = (Element) IdList.item(0);
                         
                        }
                        else {
                        // if this really can not ever be null, generate your own meaningful error message here.
                        }
                        NodeList textIdList = IdElement.getChildNodes();
                        String value = null;
    
                        Node aNode = null;
                        if (textIdList != null) {
                        aNode = (Node)textIdList.item(0);
                        if (aNode != null) {
                        value = aNode.getNodeValue();
                        if (value != null) {
                        value = value.trim();
                         }
                       }
                     }
                        System.out.println("id : " + value);
    And I get NPE on this line
    Java Code:
    NodeList textIdList = IdElement.getChildNodes();

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'd find out what the program is reading at that time and why textIdList is null. Either use a debugger or println statements. With a little sleuthing the answer should come to you. For e.g.,
    Java Code:
    if (IdElement == null) {
      System.out.println(/* a bunch of stuff here to find out where in the file you are */);
    }
    NodeList textIdList = IdElement.getChildNodes();

  13. #13
    JohnST is offline Member
    Join Date
    Dec 2009
    Posts
    20
    Rep Power
    0

    Default

    Thanks for all of your help :) I got it working!!!

  14. #14
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Haven't you ever check for null values to sort out such instance John. Or else you should catch the exception and take the proper action, basically move to the next step. Those are the simplest ways to solve this kind of errors.

Similar Threads

  1. NullPointerException
    By tommyyyy in forum New To Java
    Replies: 9
    Last Post: 03-26-2009, 10:51 PM
  2. NullPointerException I NEED HELP
    By mayhewj7 in forum New To Java
    Replies: 2
    Last Post: 02-13-2009, 08:03 AM
  3. NullPointerException
    By Aika in forum New To Java
    Replies: 8
    Last Post: 11-18-2008, 11:34 PM
  4. NullPointerException
    By adeeb in forum AWT / Swing
    Replies: 3
    Last Post: 06-11-2008, 08:42 AM
  5. NullPointerException
    By mensa in forum Java 2D
    Replies: 5
    Last Post: 05-03-2008, 11:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •