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
jjvdevjjvdev 

System.NullPointerException: Attempt to de-reference a null object Error

The line attempting to create the Set "ids" is throwing an error upon insert of a new lead.

Here is the error "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, leadTrigger: execution of BeforeInsert     caused by: System.NullPointerException: Attempt to de-reference a null object". 

How do you get the Id for trigger.new?
 
trigger leadTrigger on Lead (before insert, after insert, after update) {
    Set<ID> ids = Trigger.newMap.keySet();  // getting error here
    List<Lead> triggerLeads = [SELECT Id, Email, LeadSource FROM Lead WHERE Id in :ids];
}

 
Best Answer chosen by jjvdev
Jayant JadhavJayant Jadhav
Hi,

newMap is a map of IDs to the new versions of the sObject records and only available in before update, after insert, and after update triggers.

Remove before insert event and try again.
 

All Answers

Thiyagarajan Selvaraj (SFDC Developer)Thiyagarajan Selvaraj (SFDC Developer)
Hi jjvdev,

You need to initalize your set. Try this 
Set<ID> ids = new Set<Id>{Trigger.newMap.keySet()};

 
Jayant JadhavJayant Jadhav
Hi,

newMap is a map of IDs to the new versions of the sObject records and only available in before update, after insert, and after update triggers.

Remove before insert event and try again.
 
This was selected as the best answer
jjvdevjjvdev
Thanks Jayant!  That works.  In case others have a similar issue this is how my updated trigger looks.
 
trigger leadTrigger on Lead (before insert, after insert, after update) {

  if (trigger.isInsert && trigger.isAfter) {
    	
    	Set<ID> ids = Trigger.newMap.keySet();
    	List<Lead> triggerLeads = [SELECT Id, Email, LeadSource FROM Lead WHERE Id in :ids];
    	system.debug ('***** triggerLeads info *****'+triggerLeads);
    	
    	for(Lead l: triggerLeads) {
           // do stuff
        }
  
  }

}