Solved

java.lang.NullPointerException (probably easy)

Posted on 2006-07-23
11
485 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 500 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

Enroll in June's Course of the Month

June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

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

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Simple Linear Regression

687 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