[SalesForce] System.NullPointerException: Attempt to de-reference a null object

Error: Invalid Data. Review all error messages below to correct your
data. Apex trigger InsertContact caused an unexpected exception,
contact your administrator: InsertContact: execution of AfterUpdate
caused by: System.DmlException: Update failed. First exception on row
0 with id 00190000019XMfWAAW; first error:
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InsertContact: execution of
AfterUpdate caused by: System.NullPointerException: Attempt to
de-reference a null object Trigger.InsertContact: line 43, column 1:
[]: Trigger.InsertContact: line 43, column 1

if ( Trigger.isUpdate ) {
    //List<Account> acnt = new List<Account>();
    Account acc;
    for ( Account oldval : Trigger.old ) {
        if ( staticFun.runME ) {
            System.debug(+oldval.AccountNumber);
            System.debug(+oldval.Id);

            // Account ac = new Account(AccountNumberNew__c=Integer.ValueOf(oldval.AccountNumber));
            //acnt.add(ac);

            acc = [select AccountNumberNew__c from Account where Id =: oldval.Id];
            system.debug('account INFO:'+acc);
            acc.AccountNumberNew__c = Integer.ValueOf(oldval.AccountNumber);
            System.debug(acc.AccountNumberNew__c);

            //update acc;
            staticFun.runME = false;
        }
    }
    update acc;
    System.debug('AccountNumberNew Inserted successfully!');
}

I want to update standard AccountNumber field, while updating, old value has to be assigned to custom field AccountNumberNew__c. Kindly help me to resolve this.

Here I have used if ( staticFun.runME ) for prevent recursive trigger.

Best Answer

this is most probably happening when you try to execute this line:

update acc;

Most probably acc variable is still null at this point, which can happen because of 2 reasons:

  1. Your Trigger.old is empty, so you never get inside the loop
  2. staticFun.runMe is always false, so you never get inside this if-statement

Also, this line

acc = [select AccountNumberNew__c from Account where Id =: oldval.Id];

is a query inside the for-loop. The best practice is to move all queries outside the loops. Read about governor limits in Salesforce.