[SalesForce] Null Pointer Exception When Incrementing Variable

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;
}

Best Answer

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;
}
Related Topic