Solved

java.lang.NullPointerException (probably easy)

Posted on 2006-07-23
11
482 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
  • 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
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 
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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

This is about my first experience with programming Arduino.
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

809 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