1

Error

Attempt to de-reference a Null object.

in my below httpcallout I get above error for line

if(xroot.getChildElement('State', null).gettext() != null)

my callous code looks as below .

        resp = res.getBody();
        system.debug('res :' + resp); // resp == resXML
       Dom.Document docx = new Dom.Document();
        docx.load(resp);
        system.debug('Docx' + docx);
        Dom.XmlNode xroot = docx.getRootElement();
        if(xroot.getChildElement('ZipCode',null)!= null){
           if(xroot.getChildElement('State', null).gettext() != null){
              String state = xroot.getChildElement('ZipCode',null).getChildElement('State',null).getText();
                c.MailingState = state;
                system.debug('State'+ state);

1 Answer 1

1

Methods can't be called on a null reference; it looks like getChildElement('State',null) is returning a null value, so you should check that first:

Dom.XmlNode stateNode = xroot.getChildElement('State',null);
if(stateNode != null && stateNode.getText() != null) {

Based on the additional comment, it looks like you need to read the ZipCode node to get to the State:

Dom.XmlNode zipNode = xroot.getChildElement('ZipCode',null),
    stateNode = zipNode == null? null: zipNode.getChildElement('State',null);
if(stateNode != null && stateNode.getText() != null) {
6
  • It is not returning Null for state. Look at the response that I get. <CityStateLookupResponse><ZipCode ID="0"><Zip5>08873</Zip5><City>Somerset</City><State>NJ</State></ZipCode></CityStateLookupResponse>
    – Ricky
    Commented Apr 17, 2017 at 16:07
  • @Ricky state is a child of ZipCode, not the root element. You'll need to get the ZipCode node first.
    – sfdcfox
    Commented Apr 17, 2017 at 16:10
  • I am getting this error when I enter your modify answer."Method does not exist or incorrect signature: void get(String, NULL) from the type dom.XmlNode"
    – Ricky
    Commented Apr 17, 2017 at 16:22
  • @Ricky Yeah, it should have been getChildElement instead of get.
    – sfdcfox
    Commented Apr 17, 2017 at 16:30
  • Hey Great that worked for me. One last question if I want to get city from the same response I believe I just need to add this line "cityNode = zipNode == null? null: zipNode.getChildElement('City',null);" But when I add that I get error saying variable cityNode does not exist.can you explain?
    – Ricky
    Commented Apr 17, 2017 at 16:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .