+ Start a Discussion
Tyler Harris 8Tyler Harris 8 

Null Pointer Exception in For Loop Map

I'm trying to query attachments and add an attachment to a custom business segment object. I'm getting a null pointer exception when trying to retrieve te value from an attachment map. Any ideas on how to optimize/fix? In the debugger the map is populated with values, but I'm still getting an exception.

The error hits at this line:
if(bizAttachMap.size() > 0 && bizAttachMap.containsKey(ptrBizMap.get(psd.Partner_Account__c).Id))

Map<Id, Attachment> bizAttachMap = new Map<Id, Attachment>();
         for(Attachment attach: bizAttach){
             bizAttachMap.put(attach.ParentId, attach);
		List<Business_Segment__c> bizSegInsert = new List<Business_Segment__c>();
		List<Attachment> attachmentToInsert = new List<Attachment>();
        for(Partner_Locator_Detail__c psd : newMap.values()){
            if(acctPldMap.containsKey(psd.Partner_Account__c) && psd.Publication_Status__c=='Draft' && psd.isClone()){
                if(ptrBizMap.size() >0 && ptrBizMap.containsKey(acctPldMap.get(psd.Partner_Account__c).id)){
                    Business_Segment__c bizs = ptrBizMap.get(acctPldMap.get(psd.Partner_Account__c).id);
                    Business_Segment__c bizClone = bizs.clone(false,true);
                    bizClone.Partner_Locator_Detail__c = psd.id;
                     if(bizAttachMap.size() > 0 && bizAttachMap.containsKey(ptrBizMap.get(psd.Partner_Account__c).Id)){
                    	Attachment biza = bizAttachMap.get(ptrBizMap.get(psd.Partner_Account__c).Id);
                        Attachment bizaClone = biza.clone(false,true);
                        bizaClone.ParentId = psd.id;
         if(BizSegInsert !=null && BizSegInsert.size()>0){
             insert BizSegInsert;
         if(attachmentToInsert !=null && attachmentToInsert.size() > 0){
             insert attachmentToInsert;

Best Answer chosen by Tyler Harris 8
Prateek Singh SengarPrateek Singh Sengar
Hi Tyler,
Please add a null pointer check before your if statement to handle the null pointer issue
if(psd.Partner_Account__c != null )
if (ptrBizMap.get(psd.Partner_Account__c) != null )