3

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;
}
  • 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 Oct 18 '16 at 15:22
3

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;
}
| improve this answer | |
5

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;
| improve this answer | |
2

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;
}
| improve this answer | |
  • Thanks @maovrn have tried the code and seems to work will schedule for future runs and let you know. – Sachin Prasad Oct 18 '16 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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