• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NullPointerException when XML parsing

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My XML is:

<documento>
<cod_usuario></cod_usuario>
</documento>

Hi im using this code to take out data from the tag <cod_usuario>
but say if there ia no data im getting it as <cod_usuario></cod_usuario>
and im getting null pointer exception.
Pleeeease help....
im doing a null check but in vain :-(

nodosite = doc.getElementsByTagName ("cod_usuario");
if (nodosite.getLength() < 1)
{
XMLException xmlEx = new XMLException ("Requiere valor distinto a nulo");
throw xmlEx;
}
cod_user = nodosite.item (0).getFirstChild ().getNodeValue ();
if (cod_user == null)
cod_user = "";

regards,

Alfredo Lupe
Bolivia
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One of your chained method calls was returning null.

Use this instead:


Then you can do your check on whether cod_user is null.

Generally, a good programming practice when receiving a null pointer exception in a situation like this is to separate all the method calls on to distinct lines, since the NPE could be caused by any of these methods operating on a null object returned by the previous method call.

e.g. the getFirstChild method here is returning null, so getNodeValue fails


by splitting this into several lines like follows, it would have been easy to find your problem:

[ July 24, 2005: Message edited by: DW Bolton ]
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In that example XML, the cod_usuario Element does NOT have any children. The return from getFirstChild() must be checked.
Also note that many XML Node types return null from getNodeValue()
The JavaDocs for org.w3c.dom.Node have a convenient table showing the different types of Node.
Bill
[ July 25, 2005: Message edited by: William Brogden ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic