?
Solved

java.lang.NullPointerException (probably easy)

Posted on 2006-07-23
11
Medium Priority
?
486 Views
Last Modified: 2013-11-13
Im new to Java and getting a NullPointerException for this code...  I can't figure it out for the life of me.  I'm trying to learn from this though, so if you could be detailed in your explanations, that would be very useful.
--------------------------------------------------------------------------------------------------------
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 XMLDatabase {

      public static void main (String args[]) {

            String file = "personas.xml";
            String rowNodeId = "persona";
            int rowNumber = 2;
            String field = "strength";
            //String file = args[0];

            //getFile(file);
            //getRowArray(file, rowNodeId);
            getField(file, rowNodeId, rowNumber, field);

      }

      static Document getFile(String inFile) {

            try {

                  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                  Document doc = docBuilder.parse (new File(inFile));

                  return doc;

            } 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 ();
            }

            return null;

      }

      static NodeList getRowArray(String inFile, String inRowNodeId) {

            Document doc = getFile(inFile);

            NodeList rowArray = doc.getElementsByTagName(inRowNodeId);
            int totalRows = rowArray.getLength();

            return rowArray;

      }

      static void getField(String inFile, String inRowNodeId, int inRowNumber,String inField) {

            NodeList rowArray = getRowArray(inFile,inRowNodeId);
            Node row = rowArray.item(inRowNumber);

            if(row.getNodeType() == Node.ELEMENT_NODE) {
                  Element rowElement = (Element)row;
                  NodeList fieldNode = rowElement.getElementsByTagName(inField);

                  NodeList fieldData = rowElement.getChildNodes();

                  System.out.println(((Node)fieldData.item(0)).getNodeValue().trim());
            }

      }

}
0
Comment
Question by:jtgraphic
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 

Author Comment

by:jtgraphic
ID: 17163378
I just realized I should have another line in there:

Element fieldElement = (Element)fieldNode.item(0);

after the line:

NodeList fieldNode = rowElement.getElementsByTagName(inField);

but I still get the same error.
0
 

Author Comment

by:jtgraphic
ID: 17163389
I've modified the method "getField" to the following:

------------------------------------------------------------------------

      static void getField(String inFile, String inRowNodeId, int inRowNumber,String inField) {

            NodeList rowArray = getRowArray(inFile,inRowNodeId);
            Node row = rowArray.item(inRowNumber);

            if(row.getNodeType() == Node.ELEMENT_NODE) {
                  Element rowElement = (Element)row;
                        NodeList fieldNode = rowElement.getElementsByTagName(inField);
                        Element fieldElement = (Element)fieldNode.item(0);

                        NodeList fieldData = fieldElement.getChildNodes();
                        Element rawData = (Element)fieldData.item(0);
                        String outputData = rawData.getNodeValue().trim();

                  System.out.println(outputData);
            }

      }

------------------------------------------------------------------------

Functionally it's the same, but should be easier to read.
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 17163657
Your problem is that the item() call, on this line:

   Node row = rowArray.item(inRowNumber);

Is returning 'null'...

And you are then trying to use that 'null' object, on this line:

   if ( row.getNodeType() ...

Which is why you're getting a NullPointerException.
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 25

Expert Comment

by:InteractiveMind
ID: 17163669
If the 'inRowNumber' value is greater than or equal to the number of elements within the 'rowArray' NodeList, then the item() call will return null.

So check to see how many elements are within that NodeList, by adding the following line:

   System.out.println( rowArray.getLength() ) ;

Straight after this line:

   NodeList rowArray = getRowArray(inFile,inRowNodeId);
0
 

Author Comment

by:jtgraphic
ID: 17163688
Ha!  I can't beleive I did that.  I have two "rows" and I started at 1, not 0.

I'll have to catch that error then.

Unfortunately when I fixed the issue and recomplied I'm getting a ClassCastException here:

Element rawData = (Element)fieldData.item(0);

it seems like it should be something simple...
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 17163701
You can only cast class's.
Whereas 'Element' is an interface.

You should be fine with just this:

Element rawData = fieldData.item(0);
0
 

Author Comment

by:jtgraphic
ID: 17163705
when I pull the cast, I get this:

C:\...\Java\XMLDatabase.java:74: incompatible types
found   : org.w3c.dom.Node
required: org.w3c.dom.Element
                              Element rawData = fieldData.item(0);
                                                                        ^
1 error
0
 
LVL 25

Accepted Solution

by:
InteractiveMind earned 2000 total points
ID: 17163722
Oh, sorry.
Element extends the Node interface, not the other way around (otherwise my suggestion would work).

In that case, Node->Element is an incompatible conversion.

Fortunately however, the Node interface provides all the functionality that you need here, so you can scrap the use of Element all together:


   Node rawData = fieldData.item(0);
   String outputData = rawData.getNodeValue().trim();
0
 

Author Comment

by:jtgraphic
ID: 17163724
Excellent! That worked.

Now... one final question.

Where are you finding this information...?
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 17163740
Well, mostly: my brain.

But I must admit... when you got that ClassCastException, I had to resort to the Java API Docs:
http://java.sun.com/j2se/1.4.2/docs/api/index.html

:-)

Glad it's sorted now.
0
 

Author Comment

by:jtgraphic
ID: 17163745
Hehe, thanks.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Simple Linear Regression
Starting up a Project
Suggested Courses

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question