0

I am unable to fix the error System.NullPointerException: Attempt to de-reference a null object on my trigger.

Could someone help? Thanks

trigger Knowledge_kavKnownErrorSubscription on Knowledge__kav (after insert, after update) {

List<Known_Error_Subscription__c> kesList = new List<Known_Error_Subscription__c>();

for(Knowledge__kav kav : [SELECT Id, Known_Error_Status__c, VersionNumber, Title, KnowledgeArticleId, (SELECT Knowledge__c FROM Known_Errors_Subscriptions__r)
                          FROM Knowledge__kav WHERE Id IN :Trigger.New]) {
                             
     if(kav.KnowledgeArticleId != null &&(Trigger.oldMap.get(kav.Id).LastPublishedDate != Trigger.newMap.get(kav.Id).LastPublishedDate)) {
        Known_Error_Subscription__c kes = kav.Known_Errors_Subscriptions__r;
        kes.Knowledge__c = kav.KnowledgeArticleId;
        kesList.add(kes);
        
    }
                              
}
if(kesList.size() > 0) {
    update kesList;
}


}
1
  • Objects in relationships do not appear in trigger context until queried. So you will have to query Known_Errors_Subscriptions__r, until which it will be null, and you will get null pointer exception. Feb 28 '21 at 12:05
1

When it run on insert, Trigger.oldMap is empty, so when you say

Trigger.oldMap.get(kav.Id)

it will return NULL, and then when you say

Trigger.oldMap.get(kav.Id).LastPublishedDate 

it will give you the null pointer exception, since you are trying to get something on a NULL.

It's also possible you get a NULL pointer exception over here:

Known_Error_Subscription__c kes = kav.Known_Errors_Subscriptions__r;
kes.Knowledge__c = kav.KnowledgeArticleId;

because kav.Known_Errors_Subscriptions__r could be an empty list, so kes.Knowledge__c = kav.KnowledgeArticleId; would be referencing Knowledge__c on a non-existing kes.

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.