Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm getting a Null Pointer Exception in a utility method I wrote to update some contacts. What can I do to prevent a null pointer exception when I modify this field?

public void AddEL()
{
    //select the id and the earned Leave field to be auto-incremented
    List<Contact> lstcontact = [SELECT Id, Test_Earned_Leave__c FROM Contact];

    // run the for loop and update the earned leave field value
    for(Contact con : lstcontact)
    {   
        Con.Test_Earned_Leave__c = Con.Test_Earned_Leave__c + 1.25;
    } 

    update lstcontact;
}
share|improve this question
    
This code looks dangerous to me. There is no error checking within it, to determine whether or not it has already been run. What if a coding error or other issue causes it to be called more than once? – Brad Thomas 2 days ago
up vote 3 down vote accepted

Before adding , we have to check whether that variable is null.

public void AddEL()
{
    List<Contact> lstcontact = [SELECT Id,Test_Earned_Leave__c FROM Contact];

    for(Contact con : lstcontact)
    {
        if(con.Test_Earned_Leave__c == null)
        {
            Con.Test_Earned_Leave__c =1.25;
        }
        else
        {
            Con.Test_Earned_Leave__c = Con.Test_Earned_Leave__c+1.25;
        }
    }

    update lstcontact;
}
share|improve this answer
    
Thanks @Preya Mohandoss this works. :) – Sachin Prasad 2 days ago

This code will treat a null value as the same as a zero value and avoid the exception:

if (Con.Test_Earned_Leave__c != null) Con.Test_Earned_Leave__c += 1.25;
else Con.Test_Earned_Leave__c = 1.25;
share|improve this answer

Please try this code in your loop:

if (Con.Test_Earned_Leave__c != null) {
    Con.Test_Earned_Leave__c += 1.25;
} else {
    Con.Test_Earned_Leave__c = 1.25;
}
share|improve this answer
    
Thanks @maovrn have tried the code and seems to work will schedule for future runs and let you know. – Sachin Prasad 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.