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
srinivas pulipatisrinivas pulipati 

How to solve System.NullPointerException: Attempt to de-reference a null object

Hi,

   I created Page for Standard save controller. my page apex code given below...
public class MassEmailMessages {
public final list<id> contactids;
    public list<contact> con;
    public MassEmailMessages(apexpages.StandardController controller){
        con=[select id from contact limit 250];
        for(Integer i=0;i<250;i++){
            contactids.add(con[i].id);
        } 
    }
    public void sendEmail(){
        messaging.MassEmailMessage mail=new messaging.MassEmailMessage();
        mail.setTargetObjectIds(contactids);
        messaging.sendEmail(new messaging.MassEmailMessage[]{mail});
    } 
}

Vf Page:

<apex:page standardController="Contact" extensions="MassEmailMessages">
    <apex:form>
    <apex:commandButton value="sendEmail" action="{!sendEmail}"/>
        </apex:form>
</apex:page>



the above page and class was successfully save without error... and then when i run this page and enter the data then click save button the error given below error is occur...
System.NullPointerException: Attempt to de-reference a null object
Class.MassEmailMessages.<init>: line 7, column 1

 
Ashish DevAshish Dev
Not nessasarily your soql query is returning 250 records.
So you need to check length property in for loop like below.
 
for(Integer i=0;i<con.size();i++){
            contactids.add(con[i].id);
        }

 
Amit Chaudhary 8Amit Chaudhary 8
Please try below code. I hope that will help you
public class MassEmailMessages {
public final list<id> contactids;
    public list<contact> con;
    public MassEmailMessages(apexpages.StandardController controller)
	{
		contactids= new List<id>();
        con=[select id from contact limit 250];
        for(Integer i=0;i<250;i++){
            contactids.add(con[i].id);
        } 
    }
	
    public void sendEmail()
	{
        messaging.MassEmailMessage mail=new messaging.MassEmailMessage();
        mail.setTargetObjectIds(contactids);
        messaging.sendEmail(new messaging.MassEmailMessage[]{mail});
    } 
}
Note you forget to create object for contactids

Please check below post. I hope that will help you
1) http://amitsalesforce.blogspot.in/2015/11/default-from-address-while-sending.html
2) http://amitsalesforce.blogspot.in/2015/11/singleemailmessage-vs-massemailmessage.html

Please let us know if this will help you

Thanks
Amit Chaudhary