how to fix System.NullPointerException: Attempt to de-reference a null object in apex class using Map<parentId, child>?

anxiousAvocado picture anxiousAvocado · Sep 30, 2016 · Viewed 7.2k times · Source

Getting the error in line " taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;" becasue the ownerid field is on contact.

Contact is the parent of benefit, Here I am getting all the benefits in start method. I want to add contactid only once if it has more than one child for that I used SET. I want to use maps as I need to get the contact OwnerId field from contact object which I am fetching in the query in start method. How do I Access contact.ownerId field using a map? below is the code.

 global Database.QueryLocator start(Database.BatchableContext bc) {
    Query='select contact__r.ownerId, contact__c, Task_creation_date__c, Status__c, task_created__c, type__c from Benefit__c Where Task_creation_date__c= TODAY AND Status__c IN (\'Active\',\'Pending\') AND Task_created__c =FALSE AND Type__c!=\'Short Term Medical\'';
    return Database.getQueryLocator(query);

}

global void execute(Database.BatchableContext bc, List<Benefit__c> scope){
    // process each batch of records

    List<Contact> contacts = new List<Contact>();
    List<Task> TaskList = new List<Task>();
    set<id> conset = New set<id>();
    Map<id,benefit__c> ConMap = new map<id,Benefit__c>();
    for (Benefit__c b : scope) {
            conset.add(b.contact__c);
            ConMap.put(b.contact__c, b);
            b.task_created__c = TRUE;
     }
      system.debug('contact and its benefit------'+ConMap);
     recordsProcessed = conset.size();
     //List<Contact> tempList = new List<Contact>();
    // tempList = [Select Id,OwnerId, firstname from Contact where Id IN:(conset)];
     if(!ConMap.isEmpty())
      {
       for(Benefit__c ben : ConMap.values())
       {
        Task taskObj = new Task();
                        taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;

I want to populate contact ownerid as the task ownerid but how do I access it from the map and keep the unique contact id in the map?

Answer

Vinod Rondla picture Vinod Rondla · Oct 2, 2016

I see that the batch query does not have the filtering condition 'Contact__c != null'. So, it's possible that one of the benefit records is missing value in the 'Contact__c' field and you wouldn't find it in the map. You can solve this in two ways:

  1. Add 'Contact__c != null' to the selector query if you don't care about those records.

(Or)

  1. Check for 'null' value in the for loop as below:

    if(!ConMap.isEmpty())
    {
        for(Benefit__c ben : ConMap.values())
        {
            if(String.isBlank(ben.Contact__c)){
                /* continue;
                   or
                   throw exception()
                */
            }
    
            Task taskObj = new Task();
            taskObj.OwnerId = ConMap.get(ben.contact__c).contact__r.OwnerId;