function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Subbeh2Subbeh2 

Error: Attempt to de-reference a null object

Hi,

 

I've been trying to deploy something but I keep getting the following error:

 

Failure Message: "System.NullPointerException: Attempt to de-reference a null object", Failure Stack Trace: "Class.callOut.main: line 70, column 13 External entry point"

 

line 70:

 

 

if (getLead.Web_Form_Source__c.substring(0, 2) == 'X0') {

 code:

 

 

public class callOut {
public static boolean isApexTest=false;
    public static HttpRequest buildWebServiceRequest(String pid, String gid, String pass, String getLead, String password){
        // Build the XML Request
        string body = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:reg="http://webservice">' +
                          '<soapenv:Header/>' +
                          '<soapenv:Body>' +
                              '<reg:RegisterUserWithAutoId>' +
                                  '<reg:partnerID>'+pid+'</reg:partnerID>' +
                                  '<reg:partnerGuid>'+gid+'</reg:partnerGuid>' +
                                  '<reg:partnerPassword>'+pass+'</reg:partnerPassword>' +
                                  '<reg:clientName>'+getLead+'</reg:clientName>' +
                                  '<reg:clientPassword>'+password+'</reg:clientPassword>' +
                              '</reg:RegisterUserWithAutoId>' +
                          '</soapenv:Body>' +
                      '</soapenv:Envelope>';
        system.debug(body);

        //construct an HTTP request
        HttpRequest req = new HttpRequest();
        req.setHeader('content-type', 'text/xml; charset=utf-8');
        req.setHeader('Host','mitsweb.iitech.dk');
        req.setEndpoint('http://webservice');
        req.setMethod('POST');
        req.setBody(body); 
        return req;
    }
    
    public static String invokeWebService(Http h, HttpRequest req){
        //Invoke Web Service
        if(!isApexTest)
        {
        try{
        HttpResponse res = h.send(req);
        return res.getBody();
        }
        catch(Exception e){
        throw e;
        }
        }
        else{
        return '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><RegisterUserWithAutoId_testResponse xmlns="webservice"><RegisterUserWithAutoId_testResult><registrationResponse clientid="0" success="True" xmlns=""><clientName value="getLead" success="True" errorCode="0"/><password success="True" errorCode="0"/><loginName value="0" success="True" errorCode="0"/></registrationResponse></RegisterUserWithAutoId_testResult></RegisterUserWithAutoId_testResponse></soap:Body></soap:Envelope>';}
    }
    
    public static void handleWebServiceResponse(string xml, String password, String id){
        //Parse and apply logic to the res message
                    //string xml = res.getBody();
            string xmlRegex = '^.*clientid="';
            pattern xmlPattern = pattern.compile(xmlRegex);
            matcher xmlMatcher = xmlPattern.matcher(xml);
            List<String> result = xml.split(xmlRegex);
            List<String> result2 = result[1].split('\"');
            
            
            Lead getLead = [select id,name,email,Web_Form_Source__c from lead where id = :id];
            
            getLead.ClientPassword__c = password;
            getLead.ClientID__c = result2[0];
            update getLead;
      
            //send email
            SendMail.newLead(getLead.id, getLead.email, getLead.Web_Form_Source__c);          
    }
    
    @Future(callout=true)
    public static void main(Id id){
        
        Lead getLead = [select name,email,Web_Form_Source__c from lead where id = :id];
        
        if (getLead.Web_Form_Source__c.substring(0, 2) == 'X0') {
            string password = EncodingUtil.convertToHex(Crypto.generateDigest('MD5',Blob.valueOf(getLead.name + Crypto.getRandomInteger()))).substring(0, 8);
            
            String pid;
            String gid;
            String pass;
            
            //apply business logic
            if        (getLead.Web_Form_Source__c == 'X00001' || 
                       getLead.Web_Form_Source__c == 'X00002' ||
                       getLead.Web_Form_Source__c == 'X00003') {
                         pid = 'xxxx';
                         gid = 'xxxx';
                         pass = 'xxxx';
            
            // 4293938 Citi Bank Retail 1-2011
            } else if (getLead.Web_Form_Source__c == 'X00014' ||
                      getLead.Web_Form_Source__c == 'X00015' ||
                      getLead.Web_Form_Source__c == 'X00016') {
                         pid = 'xxxx';
                         gid = 'xxxx';
                         pass = 'xxxx';
                         
            // 4293946 Citi Bank Retail 2-2011
            } else if (getLead.Web_Form_Source__c == 'X00017' ||
                      getLead.Web_Form_Source__c == 'X00018' ||
                      getLead.Web_Form_Source__c == 'X00019') {
                         pid = 'xxxx';
                         gid = 'xxxx';
                         pass = 'xxxx';
                         
            // 4293948 Citi Bank Retail3-2011 Fee Based
            } else if (getLead.Web_Form_Source__c == 'X00020' ||
                      getLead.Web_Form_Source__c == 'X00021' ||
                      getLead.Web_Form_Source__c == 'X00022') {
                         pid = 'xxxx';
                         gid = 'xxxx';
                         pass = 'xxxx';
            }
            
            //now need to make web service callout

            //build the http request
            Http h = new Http();
            HttpRequest req = buildWebServiceRequest(pid, gid, pass, getLead.name, password);
   
            //invoke web service call 
            string xmlres = invokeWebService(h, req);
   
            //handling the response
            handleWebServiceResponse(xmlres, password, id);    
        }
    }
    
    static testMethod void testWebService(){
        //build the http request
        isApexTest=true;
        Lead l = new Lead();
        l.Email='test@test.com';
        l.Web_Form_Source__c='X00001';
        l.LastName='LastName';
        insert l;
    }
}

 

Someone please help me, I can't figure out what's wrong.

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Cory CowgillCory Cowgill

 if (getLead.Web_Form_Source__c != null && getLead.Web_Form_Source__c.substring(0, 2) == 'X0')

 

 

You need to perform a Null Pointer check on the getLead.Web_Form_Source__c. Even though you are querying for it in your SOQL, its possible it could be empty (null). Since you are invoking a substring method on the string, you need to ensure it is not null.

 

Since its null in this case, it is throwing the "Attempt to de-reference a null object." error. This is the equivalent of the Null Pointer Exception in Java.

All Answers

Cory CowgillCory Cowgill

 if (getLead.Web_Form_Source__c != null && getLead.Web_Form_Source__c.substring(0, 2) == 'X0')

 

 

You need to perform a Null Pointer check on the getLead.Web_Form_Source__c. Even though you are querying for it in your SOQL, its possible it could be empty (null). Since you are invoking a substring method on the string, you need to ensure it is not null.

 

Since its null in this case, it is throwing the "Attempt to de-reference a null object." error. This is the equivalent of the Null Pointer Exception in Java.

This was selected as the best answer
Subbeh2Subbeh2

Thanks for the solution!

V1nitV1nit

Thanks Cory Cowgill. I got the same issue and quickly resolved with the help of your post.

ziaullahkhaksarziaullahkhaksar

Please help me.... I am executing the following code but it reply to my e-mail address and shows the error "Attempt to de-reference a null object" my controller code is here.. Thank u so much in Advance.

----Controller code-----

global class EmailCardListController implements Schedulable{

global void execute(SchedulableContext SC ) {

sendMail();
}
//Did the email send successfully?
public Boolean emailSent{ get; set;}
//Create the email handler;
transient Messaging.SingleEmailMessage mailHandler = new Messaging.SingleEmailMessage();

//The recipient
// String[] emailRecipient = new String[] {'zia.s3tech@gmail.com'};
public void sendMail() {

//set the recipient
mailHandler.setToAddresses(emailRecipient );

//set the reply email address
mailHandler.setReplyTo('ziaullah_uet@yahoo.com');

//set the display name
mailHandler.setSenderDisplayName('khaksar');

//set the subject
mailHandler.setSubject('Card List');

//set the template ID
//mailHandler.setTemplateId('00X90000000wsN3');

mailHandler.setHtmlBody('This is a test e-mail from Ziaullah');

try {
Messaging.sendEmail(new Messaging.Email[] { mailHandler });
emailSent = true;

}catch(EmailException e) {
System.debug(e.getMessage());
emailSent = false;
}
}

}

------Apex Page code is here----------

<apex:page controller="EmailCardListController" action="{!sendMail}" title="Email Card List" >

<apex:outputText value="{!emailSent}" />


</apex:page>

tonantetonante

It may be a guess but the string variable emailRecipient has been commented out in the assingment statement above it befor eit is used.

I'm wondering how you got that error and did not get the "Variable undefined" error or excpetion instead.  You have had coded strings in just about every other part of your email Message mthods but emailRecipients in the toAddresses was 1) no initialized and 2) it's  intialization is commented out. Let me know if I'm wrong but that is what I can see.

 

Ridhi RidhiRidhi Ridhi
i am pulling radio button and comment box from custom object, want to show comment box on selection of no .pls help