Results 1 to 14 of 14
Thread: NullPointerException
- 12-31-2009, 08:59 PM #1
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
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 }
- 01-01-2010, 02:37 AM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Can you please post the complete error you comes with?
- 01-01-2010, 04:38 AM #3
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 :
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, doNodeList nameList = firstItemElement.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
where you would want to do this for all the other places of this pattern..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. }
And again, for places like this,
instead, do something likeSystem.out.println("type : " +
((Node)textAgeList.item(0)).getNodeValue().trim()) ;
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);
- 01-03-2010, 12:01 AM #4
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
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)
- 01-04-2010, 02:47 AM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
What you have on line 45 of the at parserTest.java file?
at parserTest.main(parserTest.java:45)
- 01-04-2010, 03:45 AM #6
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
Here is what is on line 45 of parserTest.java
Java Code:NodeList textIdList = firstIdElement.getChildNodes();
- 01-04-2010, 03:58 AM #7
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Fine, you are retrieving items here. Somehow items are not in. Did you check the content before retrieve.
- 01-04-2010, 10:04 AM #8
Moderator
- Join Date
- Apr 2009
- Posts
- 10,476
- Rep Power
- 16
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>?Java Code:NodeList firstIdList = firstItemElement.getElementsByTagName("id"); Element firstIdElement = (Element)firstIdList.item(0);
- 01-04-2010, 08:50 PM #9
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
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:
Here is section where it stops parsing in the XMLJava 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)
How do I go about fixing this? I tried what travishein but I still no luck.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><lua_gen_persisting><properties><property><name>Location Code</name><value>77040</value></property><property><name>Location Type</name><value>US (Zip Code)</value></property><property><name>Units Type</name><value>US Units</value></property><property><name>Alert Font Size</name><value>Medium</value></property><property><name>Current Font Size</name><value>Medium</value></property><property><name>Forecast Font Size</name><value>Medium</value></property><property><name>Debug Mode</name><value>Off</value></property></properties><LuaPersistentData>PersistData = {} </LuaPersistentData></lua_gen_persisting></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> ........
-
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.I tried what travishein but I still no luck.
- 01-04-2010, 09:56 PM #11
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
Here is what I tried.
And I get NPE on this lineJava 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);
Java Code:NodeList textIdList = IdElement.getChildNodes();
-
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();
- 01-04-2010, 10:51 PM #13
Member
- Join Date
- Dec 2009
- Posts
- 20
- Rep Power
- 0
Thanks for all of your help :) I got it working!!!
- 01-06-2010, 12:37 AM #14
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
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
-
NullPointerException
By tommyyyy in forum New To JavaReplies: 9Last Post: 03-26-2009, 10:51 PM -
NullPointerException I NEED HELP
By mayhewj7 in forum New To JavaReplies: 2Last Post: 02-13-2009, 08:03 AM -
NullPointerException
By Aika in forum New To JavaReplies: 8Last Post: 11-18-2008, 11:34 PM -
NullPointerException
By adeeb in forum AWT / SwingReplies: 3Last Post: 06-11-2008, 08:42 AM -
NullPointerException
By mensa in forum Java 2DReplies: 5Last Post: 05-03-2008, 11:19 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks