0

I am doing a Custom Search Page, with AND and OR Statements on the Emailmessage Object. The Search function on the email message object works correctly, however I get a null pointer Exception if I search with account or contact criteria.

If I switch part of the query to

AND (Accountid IN:ACCids  OR ContactId IN:Contids)

Instead of OR, the account and contact query works correctly, but the email message fails to work without the account being queried.

Apex Controller

public with sharing class SearchCaseEmailController {
Public List<case> ListOfcasesResult {get;set;}

public EmailMessage emailMessRef{get;set;}
public List<EmailMessage> emailMessageList{get;set;}
public String emailBody{get;set;}
public Date FromDate{get;set;}
public Date ToDate{get;set;}
public String contactName{get;set;}
public String contactEmailAddress{get;set;}
public String accountName{get;set;}
public String customerAccNumber{get;set;}
public String groupNumber{get;set;}
public String accNumFilter {get;set;}
public List<SelectOption> filterCondition{get;set;}
public String emailFromAddFilter{get;set;}
public String emailSubFilter{get;set;}
public String emailToAddFilter{get;set;}
public String emailBodyFilter{get;set;}
public String emailccFilter{get;set;}
public String contactNameFilter{get;set;}
public String accNameFilter{get;set;}
public String accNumberFilter{get;set;}
public List<Account> accountQuery{get;set;}
public List<Account> tempList{get;set;}
public List<EmailWrapper> EmailList {get;set;}




public SearchCaseEmailController(){

    emailMessageList = new List<EmailMessage>();
    emailMessRef = new EmailMessage();
    filterCondition = new List<SelectOption>();
    filterCondition.add(new SelectOption('AND','AND'));
    filterCondition.add(new SelectOption('OR','OR'));



}  
public pageReference fetchAccountSpecificCases(){ 
    Set<ID> SUBids = fetchEmailmessageIDS();
    Set<ID> ACCids =fetchAccountIDS();
    Set<ID> Contids =fetchContactIDS();
    ListOfcasesResult = new List<case>();
    EmailList = new List<EmailWrapper>();


    List<EmailMessage> emList = [SELECT Id,FromAddress,ToAddress,CcAddress ,Subject, Parentid,Textbody,MessageDate FROM EmailMessage WHERE id IN:SUBids  LIMIT 100];
    Map<Id,List<EmailMessage>> caseIdToEmails = new Map<Id,List<EmailMessage>>();
    if(!emList.isEmpty()){
        for(EmailMessage em : emList){
            if(caseIdToEmails.containsKey(em.ParentId)){
                caseIdToEmails.get(em.ParentId).add(em);
            }
            else{
                caseIdToEmails.put(em.ParentId,new List<EmailMessage>{em});
            }
        }

        List<Case> caseList = [SELECT id, Account.Name, Accountid,contactId,Contact.Name, caseNumber from Case WHERE Id IN :caseIdToEmails.keySet() OR (Accountid IN:ACCids  OR ContactId IN:Contids)  LIMIT 50];

        for(Case c : caseList){

            for(EmailMessage em : caseIdToEmails.get(c.Id)){

                EmailWrapper ew = new EmailWrapper();
                ew.emailId = em.id;                    
                ew.emailFrom = em.FromAddress;                 
                ew.emailTo = em.ToAddress;                   
                ew.emailCC = em.CcAddress;                   
                ew.subjectLine = em.Subject;                    
                ew.emailBody = em.TextBody;                    
                ew.caseId = c.id;                   
                ew.accountId = c.AccountId;                 
                ew.contactId = c.ContactId;                  
                ew.accountName = c.Account.Name;                  
                ew.contactName = c.Contact.Name;                 
                ew.CaseNumber = c.CaseNumber;
                EmailList.add(ew);

            }
        }
    }

    system.debug('Result of Account IDs'+ACCids);
    system.debug('Result of Contact IDs'+Contids);
    system.debug('DateFrom'+FromDate);
    system.debug('DateTo'+ToDate);
    //  ListOfcasesResult = [SELECT ID,Subject,Account.name,Contact.Name, caseNumber, (SELECT Id,FromAddress,ToAddress,CcAddress ,Subject, textbody FROM EmailMessages) FROM CASE WHERE AccountId IN:ACCids  OR ContactId IN:Contids  LIMIT 100];


    return null;
}

public class EmailWrapper{
    public String caseNumber{get;set;}
    public String emailId{get;set;}
    public String emailFrom {get;set;}
    public String emailTo {get;set;}
    public String emailCC {get;set;}
    public String subjectLine{get;set;}
    public String emailBody {get;set;}
    public String caseId{get;set;}
    public Case cases{get;set;}
    public String accountName{get;set;}
    public String accountId{get;set;}
    public String contactId{get;set;}
    public String contactName {get;set;}

}



public PageReference searchCaseEmails(){ 

    fetchAccountSpecificCases();

    return null;
}

Set<ID> EmailmessageIDS;                                                        //Fetching Query Subject
public Set<ID> fetchEmailmessageIDS(){
    EmailMessageIDS = new set<ID>();
    String subjectQuery = 'select Id from EmailMessage where id != null ';
    if((EmailMessRef.Subject !='' && EmailMessRef.Subject !=null) || (EmailMessRef.FromAddress !='' && EmailMessRef.FromAddress !=null)  || (EmailMessRef.ToAddress !='' && EmailMessRef.ToAddress !=null)  || (EmailMessRef.ccAddress !='' && EmailMessRef.ccAddress !=null)){

        System.debug('------------subject------: '+ EmailMessRef.Subject);
        System.debug('----FromAddress--------'+ EmailMessRef.FromAddress);
        System.debug('----Fromdate------'+ FromDate);
        System.debug('----Fromdate------'+ toDate);
        if(EmailMessRef.Subject != null  ){
            if(EmailMessRef.Subject.contains('*')){
                EmailMessRef.Subject = EmailMessRef.Subject.replace('*','');
                subjectQuery += emailsubfilter+' Subject LIKE  \'%'+EmailMessRef.Subject+'%\' ';
            }else{
                subjectQuery += emailsubfilter+' Subject = \''+EmailMessRef.Subject+'\' ';
                System.debug('----subject--------'+ EmailMessRef.Subject);
            }

        }

        if(EmailMessRef.fromAddress != null  ){
            if(EmailMessRef.fromAddress.contains('*')){
                EmailMessRef.FromAddress = EmailMessRef.FromAddress.replace('*','');
                subjectQuery += emailFromAddFilter+' fromAddress LIKE  \'%'+EmailMessRef.FromAddress+'%\' ';
            }else{
                subjectQuery += emailFromAddFilter+' FromAddress = \''+EmailMessRef.FromAddress+'\' ';
                System.debug('----FromAddress--------'+ EmailMessRef.FromAddress);
            }

        }
        if(EmailMessRef.ToAddress != null  ){
            if(EmailMessRef.ToAddress.contains('*')){
                EmailMessRef.ToAddress = EmailMessRef.ToAddress.replace('*','');
                subjectQuery += emailtoaddfilter+' toAddress LIKE  \'%'+EmailMessRef.ToAddress+'%\' ';
            }else{
                subjectQuery += emailtoaddfilter+' ToAddress = \''+EmailMessRef.ToAddress+'\' ';
                System.debug('----ToAddress--------'+ EmailMessRef.ToAddress);
            }

        }
        if(EmailMessRef.ccAddress != null  ){
            if(EmailMessRef.ccAddress.contains('*')){
                EmailMessRef.ccAddress = EmailMessRef.ccAddress.replace('*','');
                subjectQuery += emailccFilter+' ccAddress LIKE  \'%'+EmailMessRef.ccAddress+'%\'';
            }else{
                subjectQuery += emailccFilter+' ccAddress = \''+EmailMessRef.ccAddress+'\'';
                System.debug('----ccAddress--------'+ EmailMessRef.ccAddress);
            }

        } 


        System.debug('subjectresult list----------------'+ subjectQuery.replaceFirst(' id != null AND| id != null OR', ''));
        List<EmailMessage> subjectResult = database.query(subjectQuery.replaceFirst(' id != null AND| id != null OR', ''));

        for(EmailMessage ee:subjectResult){
            EmailmessageIDS.add(ee.id);
        }
    }else{
        subjectQuery = 'select Id from EmailMessage ';
        List<EmailMessage> subjectResult = database.query(subjectQuery);

        for(EmailMessage ee:subjectResult){
            EmailmessageIDS.add(ee.id);

        }
    }
    System.debug('Emailmessageids ---------------------'+ EmailmessageIDS);
    return EmailmessageIDS;

}


Set<ID> ContactIDS;
public Set<ID> fetchContactIDS(){ 
    ContactIDS = new Set<ID>();                             //Fetching Query Contacts
    System.debug('fetchContactSpecificCases=====');
    System.debug('=======contactName ===== :'+contactName );
    System.debug('=======contactEmailAddress========== :'+contactEmailAddress);
    String contactQuery = 'select Id from Contact where contact.name != null ';
    if((contactName !='' && contactName !=null) || (contactEmailAddress !='' && contactEmailAddress !=null)){


        System.debug('=======Entry contactName ========== :'+contactName );


        // APPEND CONTACT NAME
        if(contactName != null && contactName !=null ){
            if(contactName.contains('*')){
                contactName = contactName.replace('*','');
                contactQuery += ' and Name LIKE  \'%'+contactName+'%\'';
            }else{
                contactQuery += ' and Name = \''+contactName+'\'';
            }
        }
        if((contactName != '' &&  contactName !=null) && (contactEmailAddress != '' && contactEmailAddress!=null)){
            contactQuery += ' '+contactNameFilter+' ';
        }

        // APPEND CONTACT EMAIL
        if(contactEmailAddress != '' && contactEmailAddress !=null){
            if(contactEmailAddress.contains('*')){
                contactEmailAddress = contactEmailAddress.replace('*','');
                contactQuery += ' and Email LIKE \'%'+contactEmailAddress+'%\'';
            }else{
                contactQuery += ' and Email = \''+contactEmailAddress+'\'';
            }

        }
        System.debug('**************contactQuery===='+contactQuery);

        List<Contact> contactResult = database.query(contactQuery);
        System.debug('**************contactQuery===='+contactResult);
        for(contact cc:contactResult){
            ContactIDS.add(cc.id);

        }



        System.debug('contactQuery===='+contactResult);
        System.debug('contactQuery ID===='+ContactIDS);

    }
    return ContactIDS;
}


Set<ID> AccountIds = new Set<ID>();
public Set<ID> fetchAccountIDS(){                              //Fetching Query Accounts
    System.debug('fetchContactSpecificCases=====');
    String accountQuery = 'select Id from Account where ';

    if((accountName!= '' && accountName !=null) || (groupNumber !='' && groupNumber !=null) || (customerAccNumber !='' && customerAccNumber !='') ){

        if(accountName !='' && groupNumber !='' && customerAccNumber !='' ){
            if(accountName.contains('*')){
                accountName = accountName.replace('*','');
                accountQuery += ' Name LIKE \'%' + accountName + '%\'';
            }else{
                accountQuery += ' Name = \''+accountName+'\'';
            }
            accountQuery += ' '+accNameFilter+' ';
            if(customerAccNumber.contains('*')){
                customerAccNumber = customerAccNumber.replace('*','');

                accountQuery += ' Customer_Account_Number__c LIKE \'%' + customerAccNumber + '%\'';
            }else{
                accountQuery += ' Customer_Account_Number__c = \''+customerAccNumber +'\'';
            }

            accountQuery += ' '+accNumberFilter+' ';
            if(groupNumber.contains('*')){
                groupNumber = groupNumber .replace('*','');

                accountQuery += ' Group_ID__c LIKE \'%' + groupNumber + '%\'';
            }else{
                accountQuery += 'Group_ID__c = \''+groupNumber +'\'';
            }    

        }else if((accountName!= '' && accountName !=null) && (groupNumber =='' || groupNumber ==null) && (customerAccNumber =='' || customerAccNumber ==null)){
            if(accountName.contains('*')){
                accountName = accountName.replace('*','');
                accountQuery += ' Name LIKE \'%' + accountName + '%\'';
            }else{
                accountQuery += ' Name = \''+accountName+'\'';
            }
        }else if(customerAccNumber  != '' && groupNumber =='' && accountName ==''){
            if(customerAccNumber.contains('*')){
                customerAccNumber = customerAccNumber.replace('*','');

                accountQuery += ' Customer_Account_Number__c LIKE \'%' + customerAccNumber + '%\'';
            }else{
                accountQuery += ' Customer_Account_Number__c = \''+customerAccNumber +'\'';
            }

        }else if(customerAccNumber  == '' && groupNumber !='' && accountName ==''){
            if(groupNumber.contains('*')){
                groupNumber = groupNumber .replace('*','');

                accountQuery += ' Group_ID__c LIKE \'%' + groupNumber + '%\'';
            }else{
                accountQuery += 'Group_ID__c = \''+groupNumber +'\'';
            }

        }else if((accountName != '' && accountName != null) && ((customerAccNumber != '' && customerAccNumber != null) || (groupNumber !=null && groupNumber !='')) ){
            if((accountName != '' && accountName != null) && (customerAccNumber != '' && customerAccNumber != null) ){
                if(accountName.contains('*')){
                    accountName = accountName.replace('*','');
                    accountQuery += ' Name LIKE \'%' + accountName + '%\'';
                }else{
                    accountQuery += ' Name = \''+accountName+'\'';
                }


                accountQuery += ' '+accNameFilter+' ';

                if(customerAccNumber.contains('*')){
                    customerAccNumber = customerAccNumber.replace('*','');

                    accountQuery += ' Customer_Account_Number__c LIKE \'%' + customerAccNumber + '%\'';
                }else{
                    accountQuery += ' Customer_Account_Number__c = \''+customerAccNumber +'\'';
                }


            }else if((accountName != '' && accountName != null) && (groupNumber != '' && groupNumber != null) ){
                if(accountName.contains('*')){
                    accountName = accountName.replace('*','');
                    accountQuery += ' Name LIKE \'%' + accountName + '%\'';
                }else{
                    accountQuery += ' Name = \''+accountName+'\'';
                }


                accountQuery += ' '+accNameFilter+' ';

                if(groupNumber.contains('*')){
                    groupNumber = groupNumber .replace('*','');

                    accountQuery += ' Group_ID__c LIKE \'%' + groupNumber + '%\'';
                }else{
                    accountQuery += 'Group_ID__c = \''+groupNumber +'\'';
                }


            }
        }
        System.debug('accountQuery ===='+accountQuery );

        List<Account> accountResult = database.query(accountQuery);
        for(Account acc:accountResult){
            AccountIds.add(acc.id);
        }

    }
    return AccountIds;
}

I still need to update the filter criteria as seen in the subject.

The error occurs on

Error is in expression '{!searchCaseEmails}' in page searchcaseemails:
Class.SearchCaseEmailController.fetchAccountSpecificCases: line 66, column 1
Class.SearchCaseEmailController.searchCaseEmails: line 118, column 1

  • did you get the line number on which error is occurring? – Santanu Boral Nov 29 '16 at 18:49
  • You didn't include the fetchEmailMessageIds method in your post here...Please edit your question to include that method as well. – Adrian Larson Nov 29 '16 at 18:50
1

Your code assumes each Case will have EmailMessage records related to it. The solution is to check if the List<EmailMessage> is non-null before iterating over it.

I recommend you break out your for loop into a distinct method to simplify your code and testing. This strategy is simply focusing on Separation Of Concerns using Function Composition. You can compose simpler functions here as follows:

public static List<EmailWrapper> buildWrappers(Case record, List<EmailMessage> emails)
{
    List<EmailWrapper> wrappers = new List<EmailWrapper>();
    if (emails == null) return wrappers;

    for (EmailMessage email : emails)
        wrappers.add(buildWrapper(record, email));
    return wrappers;
}
public static EmailWrapper buildWrapper(Case record, EmailMessage email)
{
    // build single EmailWrapper instance based on your innermost loop
}

Then in your fetchAccountSpecificCases method, simply loop through the Case records and pass them to this delegated logic which performs a null check:

for (Case record : caseList)
    emailList.addAll(buildWrappers(record, caseIdToEmails.get(record.Id));

One more note on how you can tighten your code, I usually use a more compact grouping loop:

Map<Id, List<EmailMessage>> caseIdToEmails = new Map<Id, List<EmailMessage>>();
for (EmailMessage email : [SELECT ... FROM EmailMessage WHERE ...])
{
    if (!caseIdToEmails.containsKey(email.ParentId))
        caseIdToEmails.put(email.ParentId, new List<EmailMessage>();
    caseIdtoEmails.get(email.ParentId).add(email);
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.