Solved

java.lang.NullPointerException (probably easy)

Posted on 2006-07-23
11
481 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 25

Expert Comment

by:InteractiveMind
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 25

Expert Comment

by:InteractiveMind
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Excellent! That worked.

Now... one final question.

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

Expert Comment

by:InteractiveMind
Comment Utility
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
Comment Utility
Hehe, thanks.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

A short article about a problem I had getting the GPS LocationListener working.
Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
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 fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

728 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now