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
Abhishek KedariAbhishek Kedari 

Error in accessing fields in controller : System.NullPointerException: Attempt to de-reference a null object

Hi All,

   I have question - 
  I created one object 'sampleObject' with one field 'Name' in it and visualforce page and controller code as follows

Visualforce page code :

   <apex:page controller="SampleClass">
    <apex:form id="RID">
        <apex:pageBlock title="Sample Edit" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>           
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Basic Information" columns="1">
                <apex:inputText label="Name" value="{!sampleObj.Name__c}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Code : 

public class SampleClass {

    public sampleObject__c sampleObj { get; set; }

    public PageReference save() {     
        System.Debug(sampleObj.Name__c);
        return null;
    }
}


Now whenever I click on save button it gives me error - 

System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!save}' in component <apex:commandButton> in page samplepage: Class.SampleClass.save: line 6, column 1

Can anyone tell me where am I going wrong ?

Thanks,
Abhishek
Best Answer chosen by Abhishek Kedari
Shyam BhundiaShyam Bhundia
Hi, 

you need to initialise the sampleObj variable... 

You can do this in a constructor....

public class SampleClass {

    public sampleObject__c sampleObj { get; set; }

    public SampleClass(){
        sampleObj = new sampleObject__c();
    }

    public PageReference save() {     
        System.Debug(sampleObj.Name__c);
        return null;
    }
}




All Answers

Shyam BhundiaShyam Bhundia
Hi, 

you need to initialise the sampleObj variable... 

You can do this in a constructor....

public class SampleClass {

    public sampleObject__c sampleObj { get; set; }

    public SampleClass(){
        sampleObj = new sampleObject__c();
    }

    public PageReference save() {     
        System.Debug(sampleObj.Name__c);
        return null;
    }
}




This was selected as the best answer
James LoghryJames Loghry
As an FYI, another way you could do this is use the Standard Controller for sampleObject__c and if you have any additional logic you need, then modify your controller to be an extension controller. For an example of the standard controller / extension scenario, see this document: https://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_standardcontroller.htm (https://www.salesforce.com/us/developer/docs/pages/Content/apex_pages_standardcontroller.htm)