Mohd Nabeel
Mohd Nabeel

Reputation: 13

Attempt to de reference a null object error

On line acct.AmountX__c += amtX this and acct.AmountY__c += amtY this it is giving me an error. The trigger is on after insert and after update. When i am inserting any record in contact then it is giving me an error i don't know why. Why should 'acct' be initialized if i am not wrong this error comes when you have not initialized something.

public class ContactAccountRollUpAmount {
        public static void onAfterInsertOrUpdate(List<Contact> cont){
            contAccRollUpAmount(cont);
        }
        public static void contAccRollUpAmount(List<Contact> contactList){
            List<Contact> cont = new List<Contact>([Select AccountId, Amount_Type__c, Amount__c
                                                    from Contact 
                                                    where id in: contactList]);
            List<Account> accList = new List<Account>([Select id, AmountX__c, AmountY__c 
                                                   from Account Limit 50000]);
            List<Account> accListToUpdate = new List<Account>();
            for(Account acct: accList){
                Double amtX = 0;
                Double amtY = 0;
                system.debug('#########'+acct);
                for(Contact con: cont){
                    if(con.AccountId == acct.Id){
                        if(con.Amount__c != NULL){
                            if(con.Amount_Type__c == 'AmountX'){
                                amtX = amtX + con.Amount__c;
                            } else if(con.Amount_Type__c == 'AmountY'){
                                amtY = amtY + con.Amount__c;
                            }
                        }
                    }
                }
                if(amtX != NULL){
                    acct.AmountX__c += amtX;          
                }
                if(amtY != NULL){
                    acct.AmountY__c += amtY;
                }
                accListToUpdate.add(acct);
            }
            if(accListToUpdate.size()>0){
                update accListToUpdate;    
            }
        }
    }

Upvotes: 0

Views: 1060

Answers (1)

Aayush Shrivastava
Aayush Shrivastava

Reputation: 1

The problem is not that the 'acct' is not initialized, its the field 'AmountX__c' and 'AmountY__c'.

As I can see you have queried max of 50000 records, out of these records some of them have 'Null' values for the above two fields.

I suggest please check whether the above two fields have 'Null' values for some records or not.

Upvotes: 0

Related Questions