+ Start a Discussion
stratus adminstratus admin 

Newbie question: System.NullPointerException

Sorry, dumb newbie question. I have a trigger I am trying to configure that pulls a pick-list attribute (sales_region__c) off of the User object and is to place it on a the same named field of a custom object. This is what I have:
 
trigger SetOwnerRegion on SFL5_Projects__c (after update) {

SFL5_Projects__c pr;

 for (Integer i = 0; i < Trigger.new.size();i++){ 
  SFL5_Projects__c  ProjectNew = Trigger.new[i]; 
  SFL5_Projects__c  ProjectOld = Trigger.old[i]; 
  // we check to see if the subject has changed 
  if (ProjectNew.ownerID != ProjectOld.ownerID) {  
    user cr = [select Sales_Region__c from user where id = :ProjectNew.ownerID ]; 
    pr.Sales_Region__c = cr.Sales_Region__c;
    update pr;
   } 
 } 
}
And it is generating this error:
 
execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.SetOwnerRegion: line 11.
 
Any suggestions?
 
Thanks,
 
Scott
ckempckemp
I think you're getting this error because this line sets pr (to null, by default):
SFL5_Projects__c pr;
Then you are trying to do this:
pr.Sales_Region__c = cr.Sales_Region__c;

Since pr is null, it has no attributes like Sales_Region__c.  You have to set pr to something first.  Perhaps you could change the first line in the function to:
SFL5_Projects__c pr = new SFL5_Projects__c();
That will set the value to a new instance of the object, then you can change its attributes (which exist now.)