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
heinleinandyheinleinandy 

Simple error on a simple trigger

Hi,
I have spent a year in college on C++, and understand computer programming fairly well.
With that said, this is my first attempt and apex, triggers and SOQL (or SQL for that matter) and i could use some help.
 
Here is my apex class
 
public class calculateResources {
    public static void addResource(PersonalProject__c PP){
       
        MonthlyProject__c MP = [SELECT Hours_This_Term__c, WholeProject__c FROM MonthlyProject__c WHERE id= : PP.MonthlyProject__c];
        MP.Hours_This_Term__c += PP.hours_spent__c;
        WholeProject__c WP = [SELECT AllocatedHours__c FROM WholeProject__c WHERE id= :MP.WholeProject__c];
        WP.AllocatedHours__c += PP.hours_spent__c;
   
    }
}
 
 
and here is my trigger
 

trigger addResource on PersonalProject__c (after insert) {
    for (Integer i = 0; i < Trigger.new.size(); i++)
        calculateResources.addResource(Trigger.new[i]);
}

When I create a personal project, i need MonthlyProject__c.hours_this_term__c to update by adding personalProject__c.hours_spent__c. and similarly with whole project updating from MP.hours this term.

When i run this, i get

Apex trigger addResource caused an unexpected exception, contact your administrator: addResource: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.calculateResources.addResource: line 5, column 9

Any help would be great, i am not real sure where the null pointer is that im attempting to dereference
Thanks


Message Edited by heinleinandy on 07-07-2008 07:04 AM

Message Edited by heinleinandy on 07-07-2008 07:05 AM
MikeGoelzerMikeGoelzer
The pointer null is on line 5, column 9 of your class.  (It's at the end of the stack trace you posted.)

To fix it, either do an explicit test for null (if MP==null) or use a try block.  You probably just want to ignore the PP's that are missing all the fields, so you could just log the error and then leave the routine.
try {
        MonthlyProject__c MP = [SELECT Hours_This_Term__c,
WholeProject__c FROM MonthlyProject__c WHERE id= :PP.MonthlyProject__c];
        MP.Hours_This_Term__c += PP.hours_spent__c;
// etc.
} catch (NullPointerException e) {
System.debug('That null pointer thing happened again on ' + PP.id);
}



werewolfwerewolf
Also, once you fix this bug, your changes will not actually be saved until you call update on MP and WP.