I have a batch apex where I insert some records. I check on the fields for != null but still get the error:
Attempt to de-reference a null object
Here is my batch part:
global void execute(Database.BatchableContext bc, List<Relatie_Contact__c> scope){
// process each batch of records
if(scope.size()!=Null){
for (Relatie_Contact__c rc : Scope){
if(Scope.size() > 0) {
if(rc.Contactpersoon__r.Birthdate.year() !=null){
Integer St=System.Today().year()- rc.Contactpersoon__r.Birthdate.year();
Id relatietype;
if(rc.relatietype__c == 'Zomer Challenge' && rc.relatietype__c!=null){
relatietype = relatietype4[0].id;
}
if(St < 6 && rc.relatietype__c != 'Zomer Challenge' && rc.relatietype__c!=null){
relatietype = relatietype3[0].id;
}
if(St > 5 && St <= 17 && rc.relatietype__c != 'Zomer Challenge' && rc.relatietype__c!=null){
relatietype = relatietype2[0].id;
}
if(St > 17 && rc.relatietype__c != 'Zomer Challenge' && rc.relatietype__c!=null){
relatietype = relatietype1[0].id;
}
//If Referentie__c > 50 characters --> error in servicebus
if(rc.Contactpersoon__r.Bondsnummer__c != null && rc.Contactpersoon__r.Name !=null){
Intlenght = (String.valueOf(rc.Contactpersoon__r.Bondsnummer__c +' / ' + rc.Contactpersoon__r.Name)).length();
if(Intlenght >49 ){subjectInput = (rc.Contactpersoon__r.Bondsnummer__c +' / ' + rc.Contactpersoon__r.Name).subString(0,49) ;}
if(Intlenght <49 ){subjectInput = (rc.Contactpersoon__r.Bondsnummer__c +' / ' + rc.Contactpersoon__r.Name);}
}
Factuurregel__c fa =new Factuurregel__c(Organisatie__c=rc.Organisatie__c , Debiteur__c =rc.Organisatie__r.Debiteurennummer__c,
Aantal__c = 1, AFAS_ID__c=relatietype, Factuurdatum__c= date.today(),
Contactpersoon__c = rc.Contactpersoon__c, Referentie__c = subjectInput
);
fact.add(fa);
}
}}insert fact; fact.clear();}
}
The following line seems to throw the error:
Integer St=System.Today().year()- rc.Contactpersoon__r.Birthdate.year();
if
statement itself. If theBirthdate
field is set tonull
, you can't call theyear()
method on it. You should check if theBirthdate
field is not null.if(scope.size()!=Null)
at the start? The size of scope will never be null.Birthdate
againstnull
before doing the system.debug!