+ Start a Discussion
SamwisematrixSamwisematrix 

attempt to dereference a null object

Below is my Code.   I am getting an error that I am attepting to dereference a null object.  I am not sure how to fix it.   I am very new to writtng triggers and any help would be very appriciated. 

 

 

 

trigger LastActDate3 on Task (after insert, after update) {

Set <ID> OptyIDs = new Set <ID> ();

Set<Id> Ready4Update = new Set<Id>();

List<Opportunity> OppList = new List<Opportunity>();

for (Task t: Trigger.new){

OptyIDs.add(t.WhatID);

}

Map<ID, Opportunity> OptyMap = new Map<ID, Opportunity> ([Select ID,Last_Activity__c from Opportunity where ID in :OptyIDs]);

for (Task t: Trigger.new){

if (t.WhatID != NULL){

 

Opportunity OptyRec = OptyMap.get(t.WhatID);

If (((!t.subject.contains('Act-On Email')) )){

 

Optyrec.Last_Activity__c = t.ActivityDate;

 

}

if(!Ready4Update.contains(OptyRec.id)){

 

   OppList.add(OptyRec);   

   Ready4Update.add(OptyRec.id);

 

}

 

}

}

if(OppList.size() > 0){

update oppList;

}

}

   
 
Best Answer chosen by Admin (Salesforce Developers) 
Dhaval PanchalDhaval Panchal

Make below changes and try.

For following line

Opportunity OptyRec = OptyMap.get(t.WhatID);

 check map like below

Opportunity OptyRec = new Opportunity();
if(OptyMap.size()>0 && OptyMap.containsKey(t.WhatId)){
	OptyRec = OptyMap.get(t.WhatID);
	If (t.subject <> null && t.subject.contains('Act-On Email') == false){
		Optyrec.Last_Activity__c = t.ActivityDate;
	}
	if(!Ready4Update.contains(OptyRec.id)){
	   OppList.add(OptyRec);   
	   Ready4Update.add(OptyRec.id);
	}	
}

 

All Answers

PrathyushaPrathyusha

WhatId on a Task can be null, so try adding a null check when you are adding WhatIds to the OptyIDs set:

 

for (Task t: Trigger.new){
if(t.WhatID!=null){
OptyIDs.add(t.WhatID);

}

}

Dhaval PanchalDhaval Panchal

Make below changes and try.

For following line

Opportunity OptyRec = OptyMap.get(t.WhatID);

 check map like below

Opportunity OptyRec = new Opportunity();
if(OptyMap.size()>0 && OptyMap.containsKey(t.WhatId)){
	OptyRec = OptyMap.get(t.WhatID);
	If (t.subject <> null && t.subject.contains('Act-On Email') == false){
		Optyrec.Last_Activity__c = t.ActivityDate;
	}
	if(!Ready4Update.contains(OptyRec.id)){
	   OppList.add(OptyRec);   
	   Ready4Update.add(OptyRec.id);
	}	
}

 

This was selected as the best answer
SamwisematrixSamwisematrix

Thank you for getting back to me.  Sorry for the late reply i am just getting back to work from DreamForce. 

 

The solution you provided worked great, however when i tried to upload it into production, I recieved this error:

 

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LastActDate3: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: [] Trigger.LastAct...