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

Apex Class - Attempt to de-reference a null object error

I have a apex extension class that is supposed to save data from a visualforce page into several different objects.  The main object is contract, but the class should also update the account, opportunity, and a custom object called NSA_Agencies__c.  The NSA_Agencies__c field is not a required lookup field, so when I try to save a contract that has no agency, I get an exception - Attempt to de-reference a null object


How do I code my controller extension to only save if that lookup field is populated?  If not populated, the code should ignore that part of the save function.


Here is my extension:



withsharingclassRPM_Credit {


ApexPages.StandardController controller;

publicContract contract {get; set;}


publicOpportunity opportunity {get; set;}


publicAccount account {get; set;}


publicNSA_Agencies__c agency {get; set;}



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;



publicPageReference saveall() {








PageReference pageRef =

new PageReference('');









Thank you!!



This was the only line I saw RPM_NSA_Agency__r:


agency = contract.account.RPM_NSA_Agency__r;


and in it you are not dereferencing NSA_Agency__r you are de referencing Account


So Account on Contract has no account record if RPM_NSA_Agency__r is blank? (Since you are using the child relationship name and the record in NSA_Agency__c does not exist, therefore no child exists to get an account)


You will need to do a null check for Contract if this is correct:


If (Contract.account.size() >0)

   agency = contract.account.RPM_NSA_Agency__r;