Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 488
  • Last Modified:

java.lang.NullPointerException (probably easy)

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
jtgraphic
Asked:
jtgraphic
  • 6
  • 5
1 Solution
 
jtgraphicAuthor Commented:
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
 
jtgraphicAuthor Commented:
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
 
InteractiveMindCommented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
InteractiveMindCommented:
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
 
jtgraphicAuthor Commented:
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
 
InteractiveMindCommented:
You can only cast class's.
Whereas 'Element' is an interface.

You should be fine with just this:

Element rawData = fieldData.item(0);
0
 
jtgraphicAuthor Commented:
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
 
InteractiveMindCommented:
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
 
jtgraphicAuthor Commented:
Excellent! That worked.

Now... one final question.

Where are you finding this information...?
0
 
InteractiveMindCommented:
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
 
jtgraphicAuthor Commented:
Hehe, thanks.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now