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;
}
1
  • 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? Oct 18, 2016 at 15:22

3 Answers 3

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;
}
0
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;
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;
}
1
  • Thanks @maovrn have tried the code and seems to work will schedule for future runs and let you know. Oct 18, 2016 at 12:32

You must log in to answer this question.

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