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
Pankaj Gupta 94Pankaj Gupta 94 

Attempt to de-reference a null object Error is in expression '{!go}' in component <apex:commandButton> in page createcase: Class.assign_1_Controller.go

I have Visualforce page  with below code
<apex:page controller="assign_1_Controller">
<apex:pageBlock >
    <apex:form >
   <apex:pageBlockSection columns="1">
        <apex:inputField value="{!newCase.ContactId}" label="Search Contact">      
        </apex:inputField>
        
        <apex:commandButton value="Go" title="Go" action="{!go}"/>
        
        <!-- <apex:commandButton value="Add New Contact" title="Add New Contact" action="{!addNewContact}"/> -->
        </apex:pageBlockSection>
    </apex:form>
    </apex:pageBlock>
</apex:page>
and 

Controller
public Contact contactbyLookup{get;set;}
public PageReference go(){
        PageReference p = new PageReference('/apex/Casetabsearchassignment');
        if(newCase.ContactId != null){
        contactByLookup = [select id,
                                  Name,
                                  Business_Vertical__c  
                                  from Contact 
                                  where id =: newCase.ContactId];
    
        }
        return p;
    }
 
Best Answer chosen by Pankaj Gupta 94
Niraj Kr SinghNiraj Kr Singh
Hi Pankaj Gupta,

In your SOQL you have where condition, Where trying to get newCase.ContactId. But your newCase is having NULL value.
Replace your IF condition like:

if(newCase != null && newCase.ContactId != null)

It will avoid your Exception.

Let me kknow if it will work for you.
Mark ur Ans to help others

Thanks
Niraj

All Answers

devedeve
Hi Pankaj,

From where you are getting record in newCase. Please confirm that this variable have value beacause you are getting Attempt to de-reference a null object Error which may be due to this null variable.
Niraj Kr SinghNiraj Kr Singh
Hi Pankaj Gupta,

In your SOQL you have where condition, Where trying to get newCase.ContactId. But your newCase is having NULL value.
Replace your IF condition like:

if(newCase != null && newCase.ContactId != null)

It will avoid your Exception.

Let me kknow if it will work for you.
Mark ur Ans to help others

Thanks
Niraj
This was selected as the best answer
Pankaj Gupta 94Pankaj Gupta 94
Thanks Niraj that resolved my issue.
How ever the value was not coming so I initialize the variable  like newCase = new Case();