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
BrandiTBrandiT 

Visualforce/Apex Error: Attempt to de-reference a null object

I have a visualforce page that is supposed to update several objects at once: contract, opportunity, account, parent.parent account; Agency__c.

 

I'm getting this error message:  Attempt to de-reference a null object

 

I'm pretty sure I know why I'm getting this message already, I'm just not sure how to fix it.  On my test account, the NSA_Agencies__c lookup field is null.  What I need to know is how do I modify my apex class to check for nulls before the code tries to do the update.  The part of the code in red updates all related records that might be affected, but should really be modified to ensure the fields are populated first.  What is the format for this null check?

 

Here is my apex class:

public with sharing class RPM_Credit {
   
    ApexPages.StandardController controller;
    public Contract contract {get; set;}

    public Opportunity opportunity {get; set;}
   
    public Account account {get; set;}
   
    public NSA_Agencies__c agency {get; set;}
   
    public Account parent {get; set;}

     
public RPM_Credit(ApexPages.StandardController con){
                            controller = con;

contract = (Contract) controller.getRecord();

opportunity = contract.Opportunity__r;

account = contract.account;

agency = contract.account.RPM_NSA_Agency__r;

parent = contract.account.parent.parent;
                                                      
                                                 }                                  
  public PageReference saveall() {

           update opportunity;
           update account;
           update agency;
           update parent;
           controller.save(); 
          
           PageReference ref = new PageReference('/00O70000003JDRo');
            ref.setRedirect(true);
       
    return ref;
            }

   

}

 

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Damien_Damien_

if (opportunity != null)

  update opportunity;

 

//Go down the line doing this.  Is this what you meant?