Saturday, 15 March 2014

Attempt to de-reference a null object salesforce

Thought of posting about a very common error we come across in apex. You must have seen this a number of times.
Visualforce Error: System.NullPointerException: Attempt to de-reference a null object

This error occurs whenever you try to access value/values from a variable/collection whose new new instance has not been created or is null in other words.

for example: if you have a list of accounts (List<account> accList) defined and you have not created a new instance of this list. And then, accidentally you try to access record from this list; then you will get the above error.

As can be seen from this example:

Visualforce Page


?
1
2
3
4
5
<apex:page controller="DeferenceDemoController">
 <apex:form >
   <apex:commandButton value="Call Method" action="{!Demo_method}"/>
 </apex:form>
</apex:page>

Controller
?
1
2
3
4
5
6
7
8
9
10
Public with sharing class DeferenceDemoController {
List<account> accList;
   Public DeferenceDemoController(){
     
   }
  Public void Demo_method(){
   for(Account ac:accList )
       system.debug('****'+ac.name);
  
}




A list "accList" of accounts has been defined but a new instance of this list has not been created. So when we press the button "Call Method" we get the error "Attempt to deference a null object" as in the called method we are trying to access the "accList" list.

This error can be avoided by creating a new instance of the accList before trying to access it as below:

Modified controller:

?
1
2
3
4
5
6
7
8
9
10
Public with sharing class DeferenceDemoController {
List<account> accList;
   Public DeferenceDemoController(){
      accList =New List<account>();
    }
  Public void Demo_method(){
   for(Account ac:accList )
       system.debug('****'+ac.name);
  
}

No comments:

Post a Comment