function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
OutsiderOutsider 

Attempt to de-reference a null object

Hi Friends,

 

I have similar code to update no. of contacts in Account for Contacts insert and deletion but only got error message "Attempt to de-reference a null object".  Who can tell me why?  Thanks.

 

Code for update

 

trigger UpdateAccountNoOfBabiesbeforedeleteContact on Contact (before delete) {
    Contact[] tempnew = trigger.new;
    for(integer i =0; i<tempnew.size();i++){
        list<Account> accountList = [Select id,No_of_Contacts__c from Account where id = :tempnew[i].Account.id];
        for(Account c : accountList){
            if(c.No_of_Contacts__c ==NULL){
                c.No_of_Babies__c = 0;}
                else {
                integer tempint = integer.valueof(string.valueof(c.No_of_Contacts__c));
                tempint--;
                c.No_of_Contacts__c = decimal.valueof(tempint);
                update c;
            }//end else
        }//end for
     }//end for
}

ScoobieScoobie

trigger.new does not exist on delete events. Use trigger.old instead.

 

trigger.old is the object before the change was made. trigger.new is what it will be after the event has completed. Therefore in this instance trigger.old is your object and trigger.new is null!

OutsiderOutsider

Oh Yes, many thanks.  Now it cannot deduct 1 from the No. of Contacts.  Do you know why?

ScoobieScoobie

This isn't tested or debugged but use it as a starting point.

 

trigger UpdateAccountNoOfBabiesbeforedeleteContact on Contact (before delete) {    

    Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();

     for (Contact con : trigger.old) {

         if (contactsByAccountId.containsKey(con.AccountId)) {    

            contactsByAccountId.get(con.AccountId).add(con);

         } else {    

            contactsByAccountId.put(con.AccountId, con);

         }

     }

     Map<Id, Account> accountsById = new Map<Id, Account>([SELECT Id, No_Of_Contacts__c

                                                                                                            FROM Account

                                                                                                            WHERE Id :contactsByAccountId.keySet()]);

      for(Id accountId : contactsByAccount.keyset()) {    

        accountsById.get(accountId).No_Of_Contacts__c = accountsById.get(accountId).No_Of_Contacts__c -                                                                                                                             contactsByAccountId.get(accountId).size();

     }

      update(accountsById.values());

}

 

OutsiderOutsider

What is the difference between yours and mine?

ScoobieScoobie

Mine won't blow the governor limits when multiple contacts are deleted.

OutsiderOutsider

got an error

 

Incompatible value type SOBJECT:Contact for MAP<Id,LIST<Contact>> at line 7 column 13

ScoobieScoobie

As I say, it's untested and written on notepad, you'll have to debug it manually as I don't know how your objects are set up / configured.

 

Line 7 should be 

List<Contact> temp = new List<Contact>();

temp.add(con);

contactsByAccountId.put(con.AccountId, temp);

OutsiderOutsider

Now it deducts 2 for 1 contact record deletion

.

OutsiderOutsider

Sorry that I am new to this development and not familiar with the environment.  I may have many questions.

 

Also, I change code to add 1 to no. of contacts when insert Contact record.  It works in online entry but not in dataloader.  May I know how to make it work in both online entry and dataloader? 

ziaullahkhaksarziaullahkhaksar

Please help me.... I am executing the following code but it reply to my e-mail address and shows the error "Attempt to de-reference a null object" my controller code is here.. Thank u so much in Advance.

----Controller code-----

global class EmailCardListController implements Schedulable{

global void execute(SchedulableContext SC ) {

sendMail();
}
//Did the email send successfully?
public Boolean emailSent{ get; set;}
//Create the email handler;
transient Messaging.SingleEmailMessage mailHandler = new Messaging.SingleEmailMessage();

//The recipient
// String[] emailRecipient = new String[] {'zia.s3tech@gmail.com'};
public void sendMail() {

//set the recipient
mailHandler.setToAddresses(emailRecipient );

//set the reply email address
mailHandler.setReplyTo('ziaullah_uet@yahoo.com');

//set the display name
mailHandler.setSenderDisplayName('khaksar');

//set the subject
mailHandler.setSubject('Card List');

//set the template ID
//mailHandler.setTemplateId('00X90000000wsN3');

mailHandler.setHtmlBody('This is a test e-mail from Ziaullah');

try {
Messaging.sendEmail(new Messaging.Email[] { mailHandler });
emailSent = true;

}catch(EmailException e) {
System.debug(e.getMessage());
emailSent = false;
}
}

}

------Apex Page code is here----------

<apex:page controller="EmailCardListController" action="{!sendMail}" title="Email Card List" >

<apex:outputText value="{!emailSent}" />


</apex:page>