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
apple_saeapple_sae 

Attempt to de-reference a null object

Hi All,

 

I have Visualforce Page to list the case and have function to send email with attachment below the cases but I got the error like this:

 

Attempt to de-reference a null object

Error is in expression '{!send}' in component <apex:page> in page sendemailpage
 
public class outboundMessage {
	
    public Id cid;
    public Contact contact;
    public list<Case> cases {get; set;}
    public String attId{get;set;}
    public String addresses{ get; set;}

    // Create a constructor that populates the Account object 
    
    public outboundMessage() {
    	cid = ApexPages.currentPage().getParameters().get('id');
    	getContact();
    	getCases();        
    }
	
    public void getContact() {
    	contact = [Select	Contact.Id,
				Contact.Name,
				Contact.FirstName,
				Contact.LastName,
				Contact.Phone,
				Contact.Email,
				Contact.MailingStreet,
   				Contact.MailingCity,
   				Contact.MailingState,
   				Contact.MailingPostalCode,
   				Contact.MailingCountry
   		    From	Contact
                    WHERE       Contact.Id = :cid];
    }
    
    public void getCases(){
    	if(cid != null){
    	cases = [Select	Case.Id,
			Case.CaseNumber,
			Case.Subject,
			Case.CreatedDate,
			Case.Description,
			Case.ClosedDate,
   			(SELECT	Attachment.Id, Attachment.Name	    					 
			FROM	Case.Attachments)
    		From	Case
    		Where	Case.ContactId = :cid];
    	}
    }
    
	public String attstrMessage{
        get{
             if(attstrMessage != null){
                return  attstrMessage;
              }else{
                  return '';
              }          
         }
          private set;
        } 
         
    public PageReference send() {
    	PageReference pageReference =  ApexPages.currentPage();        
    	try{
    	Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
        
        List<Messaging.EmailFileAttachment> efas = new List<Messaging.EmailFileAttachment>();
		
   	    for(Attachment a : [select	Attachment.Id,
   	    				Attachment.Name,  
   	    				Attachment.Body 
   	    			from 	Attachment 
   	    			where 	Attachment.Id = :attId]){
    	
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName(a.Name);
	    	efa.setBody(a.body);
			efas.add(efa);
   	   }
		
		String[] toAddresses = addresses.split(':', 0);	
		
        // Sets the paramaters of the email 
    
        email.setTargetObjectId(cid);        
        email.setSaveAsActivity(false);       
        email.setTemplateId('00X90000000fCao');
        email.setToAddresses( toAddresses );        
        email.setFileAttachments(efas);
		
	Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
	        if (results[0].isSuccess()) {
	               if(efas.size() > 0){
	                    pageReference.getParameters().put('message',' Email has been resent successfully with attachments.');
	               }else{
	                pageReference.getParameters().put('message',' Email has been resent successfully .');
	               }
	               attstrMessage=''; 	                      
	         } else {
	             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,  'Failed to resend Email.'));
	             pageReference.getParameters().put('messagefail',' Failed to resend Email.');
	         }
	         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,  'Email has been resent successfully '+attstrMessage+'.'));
		}catch(System.EmailException ex ){
             system.debug('============== email exception caught!!!============='+ex.getMessage());
              pageReference.getParameters().put('messagefail',' Failed to resend Email.');
              ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,  'Failed to resend Email.'));
        }
		return ApexPages.currentPage();
    }
}

 

 
<apex:page showHeader="false" standardStylesheets="false" sidebar="false" Controller="outboundMessage" >
<apex:messages />
	
	<apex:repeat value="{!cases}" var="c">
    	<ul class="your-docs docs">
        <li  class="your-doc doc">
           <h4 class="doc-title">
           	<apex:outputText value="{!c.CaseNumber}"/> <apex:outputText value="{!c.Subject}"/>&raquo;
           </h4>
           <div class="doc-desc">{!c.Description}</div>
		<div class="record" id="recordEmail">
			<div class="data-wrapper">
				<ul class="doc-operations">
				<li>Edit</li>
		               	<li class="operations"><a href="#">Email</a></li>
		               	<li>Print</li>
				</ul>
			</div>
			<div class="form-wrapper">
				<apex:form >
					<apex:outputLabel value="email" for="Addressed"/>:
					<apex:inputText value="{!addresses}" id="addresses" maxlength="80"/>			<apex:repeat value="{!c.Attachments}" var="att">							 
					attachment name: <apex:outputText value="{!att.name}"/>
					<div class="form-actions">
                        	            <button class="cancel">Cancel</button>
					    <apex:commandButton value="Send Email" action="{!send}" styleClass="button-medium">
					    <apex:param name="attSend" value="{!att.Id}" assignTo="{!attId}"></apex:param>	
					   </apex:commandButton>
		                        </div>
					</apex:repeat>	 
				    </apex:form>
				</div>
			</div>
		</li>
		</ul>
	</apex:repeat>	
</apex:page>

 

20.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
15:31:42.014 (14629000)|EXECUTION_STARTED
15:31:42.014 (14672000)|CODE_UNIT_STARTED|[EXTERNAL]|06690000001qGv5|VF: /apex/sendEmailPage
15:31:42.014 (14890000)|VF_DESERIALIZE_VIEWSTATE_BEGIN|06690000001qGv5
15:31:42.029 (29723000)|VF_DESERIALIZE_VIEWSTATE_END
15:31:42.030 (30622000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000001ziVK|outboundMessage get(cases)
15:31:42.030 (30640000)|SYSTEM_MODE_ENTER|true
15:31:42.030 (30660000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000001ziVK|cases
15:31:42.030 (30697000)|METHOD_ENTRY|[1]|01p90000001ziVK|outboundMessage.outboundMessage()
15:31:42.030 (30794000)|METHOD_EXIT|[1]|outboundMessage
15:31:42.030 (30808000)|CODE_UNIT_FINISHED|cases
15:31:42.030 (30819000)|CODE_UNIT_FINISHED|outboundMessage get(cases)
15:31:42.037 (37406000)|CODE_UNIT_STARTED|[EXTERNAL]|01p90000001ziVK|outboundMessage invoke(send)
15:31:42.037 (37501000)|SYSTEM_METHOD_ENTRY|[60]|ApexPages.currentPage()
15:31:42.037 (37589000)|SYSTEM_METHOD_EXIT|[60]|ApexPages.currentPage()
15:31:42.038 (38499000)|SYSTEM_CONSTRUCTOR_ENTRY|[66]|<init>()
15:31:42.038 (38530000)|SYSTEM_CONSTRUCTOR_EXIT|[66]|<init>()
15:31:42.038 (38564000)|METHOD_ENTRY|[68]|01p90000001ziVK|outboundMessage.__sfdc_attId()
15:31:42.038 (38595000)|METHOD_EXIT|[68]|01p90000001ziVK|outboundMessage.__sfdc_attId()
15:31:42.038 (38890000)|SOQL_EXECUTE_BEGIN|[68]|Aggregations:0|select Attachment.Id, Attachment.Name, Attachment.Body from Attachment 
15:31:42.044 (44173000)|SOQL_EXECUTE_END|[68]|Rows:0
15:31:42.044 (44229000)|SYSTEM_METHOD_ENTRY|[68]|Database.QueryLocator.iterator()
15:31:42.044 (44327000)|SYSTEM_METHOD_ENTRY|[7]|QueryLocatorIterator.QueryLocatorIterator()
15:31:42.044 (44341000)|SYSTEM_METHOD_EXIT|[7]|QueryLocatorIterator
15:31:42.044 (44401000)|SYSTEM_METHOD_EXIT|[68]|Database.QueryLocator.iterator()
15:31:42.044 (44417000)|SYSTEM_METHOD_ENTRY|[68]|Database.QueryLocatorIterator.hasNext()
15:31:42.044 (44436000)|SYSTEM_METHOD_EXIT|[68]|Database.QueryLocatorIterator.hasNext()
15:31:42.044 (44453000)|METHOD_ENTRY|[80]|01p90000001ziVK|outboundMessage.__sfdc_addresses()
15:31:42.044 (44478000)|METHOD_EXIT|[80]|01p90000001ziVK|outboundMessage.__sfdc_addresses()
15:31:42.044 (44514000)|EXCEPTION_THROWN|[80]|System.NullPointerException: Attempt to de-reference a null object
15:31:42.046 (46629000)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

Class.outboundMessage.send: line 80, column 1
15:31:42.046 (46641000)|CODE_UNIT_FINISHED|outboundMessage invoke(send)

 

Thank for any help ! ! !

 
 
 
 
 
kiranmutturukiranmutturu

String[] toAddresses = addresses.split(':', 0);  

 

in the above line  no value is set to addresses property but using with split function which is null.. so please fill the value before using or null check the variable 

apple_saeapple_sae

Hi kiran_mutturu

 

I have public String addresses{ get; set;} in my controller and receive from Visualforce Page,
What I supposed to do anymore.

 

<apex:form >
  <apex:outputLabel value="email" for="Addressed"/>:
  <apex:inputText value="{!addresses}" id="addresses" maxlength="80"/>
  <apex:repeat value="{!c.Attachments}" var="att">							 
    attachment name: <apex:outputText value="{!att.name}"/>
   <div class="form-actions">
     <button class="cancel">Cancel</button>
     <apex:commandButton value="Send Email" action="{!send}" styleClass="button-medium">
        <apex:param name="attSend" value="{!att.Id}" assignTo="{!attId}"></apex:param>	
     </apex:commandButton>
   </div>
  </apex:repeat>	 
</apex:form>

 

kiranmutturukiranmutturu

i dont know why that block of code is not displaying for me in your earlier post any ways u r trying to set the value from vf page then its ok.....and from the debug i saw the attachement query isreturning 0 rows may b that is cauing error as you are setting the empty list to emailsetattachments 

Raj.ax1558Raj.ax1558

Try this -

public void getCases(){
cases = new list<case>()    	
if(cid != null){




} Remaining code is same.
apple_saeapple_sae

Hi Raj,

 

Thank you I already tried that it still same.

crop1645crop1645

This may help:

 

1. When using Messaging.sendEmail and templates, I think you need to also set the value of email.setWhatId(myWhatId). This tells the template what the master object is for use in the template's merge fields. If this is null, merge fields won't know what to do

 

And .. for later

 

2. You should not use hard-coded IDs for templates as they won't always preserve in some deployment scenarios (such as your template is first created in sandbox, then deployed to PROD). Instead,locate the template via a SOQL select on the template developer name or fetch from a custom setting