How do I attempt to de reference a null object?

46    Asked by AlisonKelly in Salesforce , Asked on Sep 23, 2022

I am new to Salesforce Apex coding and I am getting this null pointer exception error when I try to run a scheduled batch. Please help me as I am unable to understand the mistake I made. The code is working on insert records, but it fails when I try to run a scheduled batch. The issue is related to passing parameters when calling the batch class in scheduled batch but i do not know how to do that?


APEX TRIGGER:


trigger ILM_ReferralAddressBatch on Referral__c (after insert, After Update) {
    If(Trigger.isAfter){
        if(Trigger.isInsert){
            List referralList = new List();
            List referralListWithAddress = new List();
            Id recordTypeFibreEvent = Schema.SObjectType.Referral__c.getRecordTypeInfosByDeveloperName().get('Fibre_Event').getRecordTypeId();
            Id recordTypeISRReferral = Schema.SObjectType.Referral__c.getRecordTypeInfosByDeveloperName().get('ISR_Referral').getRecordTypeId();  
            for(Referral__c ref : Trigger.new){
                if(String.isBlank(ref.Address__c) && ref.recordTypeId == recordTypeISRReferral){
                    referralList.add(ref.Id);
                }
                if(String.isNotBlank(ref.Address__c) && ref.recordTypeId == recordTypeFibreEvent){
                    referralListWithAddress.add(ref.Id);
                }  
            } 
            system.debug('referralList--'+referralList.size());
            system.debug('referralListWithAddress----'+referralListWithAddress.size());
            if(referralList.size() > 0  || referralListWithAddress.size()>0){
                system.debug('::::: referralList' + referralList.size());
                ILM_ReferralAddressBatch objBatch = new ILM_ReferralAddressBatch(referralList, referralListWithAddress);
                Database.executebatch(objBatch,20);
            } 
        }
    }
}

Apex Class:


Global class ILM_ReferralAddressBatch implements Database.Batchable {
    private List referralIds;
    private List referralIdsWithAddress;
       
    global ILM_ReferralAddressBatch(){
        system.debug('Test');
    }
   
    global ILM_ReferralAddressBatch(List referralIds, List referralIdsWithAddress) {
        system.debug('1--In constructor');
        this.referralIds = new List(referralIds);
        this.referralIdsWithAddress = new List(referralIdsWithAddress);
        system.debug('2--referralIdsWithAddress--'+this.referralIdsWithAddress);
    }
    
    global Database.Querylocator start(Database.BatchableContext bc) {
        System.debug('this--'+this);
        system.debug('Hashcode--'+this.hashCode());
        String soqlQuery = '';
        system.debug('3--referralIdsWithAddress log---'+this.referralIdsWithAddress);
        if(this.referralIdsWithAddress.size()>0 && this.referralIdsWithAddress != null){
            //   if(this.referralIdsWithAddress.size()>0){
            soqlQuery =   'select Id,Consent_Received__c,Address__c from Referral__c where Address__c!=null AND Id IN:referralIdsWithAddress';
        }
        else{
            soqlQuery =   'select Id, Street_Name__c, Street_Number__c, Street_Type__c,' +
                'Apartment_Unit_Number__c, City__c, Zip_Postal_Code__c from Referral__c' +
                ' where Address__c = null AND Street_Name__c !=  null '+
                ' AND Street_Number__c!= null AND ((Referral_Type__c = 'Marketing Alliance''+
                ' OR  Referral_Type__c = 'New Construction''+      
                ' OR  Referral_Type__c = 'Placeholder 3') OR (Referral_Type__c = 'Placeholder 1' AND Base_Marketing_Subtype__c = 'MA - Move Out'))';
            if(this.referralIds != null && this.referralIds.size()>0){
                soqlQuery += ' AND Id IN:referralIds';
            }
        }
        return database.getquerylocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext bc, List refList){
        system.debug(':::::refList' + refList.size());
        if(refList.size()>0){
            if(this.referralIds.size()>0){
                List listToUpdate = new List();
                for(Referral__c ref: refList){
                    Address__c addressObj = null;    
                    if(String.isNotBlank(ref.City__c) && String.isNotBlank(ref.Zip_Postal_Code__c)){  
                        //check by city & postal code
                        Address__c[] addressList = [SELECT Id, City__c, Postal_Zip_Code__c, Sam_Key__c FROM Address__c
                                                    WHERE Street_name__c = :ref.Street_Name__c  
                                                    and Street_number__c = :ref.Street_Number__c
                                                    and Street_type__c = :ref.Street_Type__c
                                                    and ApartNum__c = :ref.Apartment_Unit_Number__c
                                                    and City__c =  :ref.City__c
                                                    and Postal_Zip_Code__c= :ref.Zip_Postal_Code__c
                                                    and (ADDR_COMPANY__c Like '2%'
                                                         or   ADDR_COMPANY__c Like '1%')
                                                    and  SAM_KEY__c Like '2%'LIMIT 1];
                        if(addressList.size()>0){
                            addressObj = addressList[0];
                        }else{
                            //check by city
                            Address__c [] addressList2 = [SELECT Id, City__c, Postal_Zip_Code__c, Sam_Key__c FROM Address__c
                                                          WHERE Street_name__c = :ref.Street_Name__c  
                                                          and Street_number__c = :ref.Street_Number__c
                                                          and Street_type__c = :ref.Street_Type__c
                                                          and ApartNum__c = :ref.Apartment_Unit_Number__c
                                                          and City__c =  :ref.City__c
                                                          and (ADDR_COMPANY__c Like '2%'
                                                               or ADDR_COMPANY__c Like '1%')
                                                          and SAM_KEY__c Like '2%'LIMIT 1];
                            if(addressList2.size()>0){
                                addressObj = addressList2[0];
                            }
                            else If (string.isnotblank(ref.Apartment_Unit_Number__c)){
                                Pattern pat = Pattern.compile('([0-9]+)');
                                Pattern pat2 = Pattern.compile('([A-Za-z]+)');
                                Matcher matcher = pat.matcher(ref.Apartment_Unit_Number__c);
                                Matcher matcher2 = pat2.matcher(ref.Apartment_Unit_Number__c);
                                String numOnly='';
                                if(matcher.find()){
                                    numOnly = matcher.group();
                                }
                                String StrOnly='';
                                if(matcher2.find()){
                                    StrOnly = matcher2.group();
                                }
                                Address__c [] addressList3 = [SELECT Id, City__c, Postal_Zip_Code__c, Sam_Key__c FROM Address__c
                                                              WHERE Street_name__c = :ref.Street_Name__c and Street_number__c = :ref.Street_Number__c
                                                              and Street_type__c = :ref.Street_Type__c and ApartNum__c = :numOnly
                                                              and House_Suffic_Code__c = :StrOnly                  
                                                              and City__c =  :ref.City__c and (ADDR_COMPANY__c Like '2%'
                                                                                               or ADDR_COMPANY__c Like '1%') and  SAM_KEY__c Like '2%'LIMIT 1];
                                if(addressList3.size()>0){        
                                    addressObj = addressList3[0];
                                }
                            }
                        }
                    }else if(String.isNotBlank(ref.City__c)){
                        Address__c [] addressList = [SELECT Id, City__c, Postal_Zip_Code__c, Sam_Key__c FROM Address__c
                                                     WHERE Street_name__c = :ref.Street_Name__c and Street_number__c = :ref.Street_Number__c
                                                     and Street_type__c = :ref.Street_Type__c and ApartNum__c = :ref.Apartment_Unit_Number__c
                                                     and City__c =  :ref.City__c and (ADDR_COMPANY__c Like '2%'
                                                                                      or ADDR_COMPANY__c Like '1%') and  SAM_KEY__c Like '2%'LIMIT 1];
                        if(addressList.size()>0){
                            addressObj = addressList[0];
                        }else if (string.isnotblank(ref.Apartment_Unit_Number__c)) {
                            Pattern pat = Pattern.compile('([0-9]+)');
                            Pattern pat2 = Pattern.compile('([A-Za-z]+)');
                            Matcher matcher = pat.matcher(ref.Apartment_Unit_Number__c);
                            Matcher matcher2 = pat2.matcher(ref.Apartment_Unit_Number__c);
                            String numOnly='';
                            if(matcher.find()){
                                numOnly = matcher.group();
                            }
                            String StrOnly='';
                            if(matcher2.find()){
                                StrOnly = matcher2.group();
                            }
                            Address__c [] addressList2 = [SELECT Id, City__c, Postal_Zip_Code__c, Sam_Key__c FROM Address__c
                                                          WHERE Street_name__c = :ref.Street_Name__c and Street_number__c = :ref.Street_Number__c
                                                          and Street_type__c = :ref.Street_Type__c and ApartNum__c = :numOnly
                                                          and House_Suffic_Code__c = :StrOnly                  
                                                          and City__c =  :ref.City__c and (ADDR_COMPANY__c Like '2%'
                                                                                           or ADDR_COMPANY__c Like '1%') and  SAM_KEY__c Like '2%'LIMIT 1];
                            if(addressList2.size()>0){
                                addressObj = addressList2[0];
                            }
                        }                
                    }
                    //updating record
                    if(addressObj != null){
                        listToUpdate.add(new Referral__c(
                            Id = ref.Id,
                            City__c = addressObj.City__c,
                            Zip_Postal_Code__c = addressObj.Postal_Zip_Code__c,
                            Sam_Key__c = addressObj.SAM_KEY__c,
                            Address__c = addressObj.Id,
                            Batch_Status__C = 'Pending'));
                    }
                }
                system.debug('::::: listToUpdate'  + listToUpdate.size());
                if(listToUpdate.size()>0)
                    update listToUpdate;
            }            
            if(this.referralIdsWithAddress.size()>0){
                List
listToUpdate = new List
();
                Map addressIdWithConsentStatus = new Map();   
                for(Referral__c ref: refList){
                    addressIdWithConsentStatus.put(ref.Address__c,ref.Consent_Received__c);
                }
                List
addList = [select id,Consent_Received__c from Address__c where ID IN:addressIdWithConsentStatus.keySet()];
                for(Address__c addressRec : addList){
                    if(addressIdWithConsentStatus.containsKey(addressRec.Id)){
                        addressRec.Consent_Received__c = addressIdWithConsentStatus.get(addressRec.Id) == true ? 'Yes' : 'No';
                    }
                }
                if(addList.size()>0)
                    update addList;
            }
        }
    }
    Public void finish(Database.BatchableContext bc){
        
    }
}
SCHEDULED CLASS:
global class ILM_ScheduledReferralbatch implements Schedulable {
    global void execute(SchedulableContext sc) {
        ILM_ReferralAddressBatch b = new ILM_ReferralAddressBatch();
        database.executebatch(b, 20);
    }
}

ERROR:


Apex script unhandled exception by user/organisation: 0052B000000HyAB/00D1U000000sNOI Failed to process batch for class 'ILM_ReferralAddressBatch' for job id '707Af000003160L' caused by: System.NullPointerException: Attempt to de-reference a null object Class.ILM_ReferralAddressBatch.start: line 22, column 1

Answered by Amanda Hawes

The issue here is if(this.referralIdsWithAddress.size()>0 && this.referralIdsWithAddress != null){


You need to reverse the check. First check for null and then check for size. Otherwise if this.referralIdsWithAddress is null then this.referralIdsWithAddress.size() will throw Attempt to de reference a null object

if(this.referralIdsWithAddress != null && this.referralIdsWithAddress.size()>0){

Your Answer

Interviews

Parent Categories