[SalesForce] Argument 1 Cannot be Null in For Loop

I have the below method that populates a selectlist on a VF page:

User u = [SELECT Id, ContactId, FirstName FROM User WHERE Id = :UserInfo.getUserId()];
Contact c = [SELECT Id, LastName, AccountId FROM Contact WHERE Id =:u.ContactId];
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
List<CustomObject__c> sn = [SELECT Id, Name, Service_Offering__r.Display_Name__c FROM CustomObject__c WHERE Account__c = :a.Id];
List<Service_Offering__c> serviceList = new List<Service_Offering__c>();
public List<SelectOption> getSNANAMatch(){
    Set<SelectOption> DeDupedHPList = new Set<SelectOption>();
    DeDupedHPList.add(New SelectOption('Not Health Plan Related', 'Not Health Plan Related'));
    List<String> HealthPlanStrings = New List<String>();
    for (CustomObject__c snanas : sn){
        HealthPlanStrings.add(snanas.Service_Offering__r._Display_Name__c);
    }
    HealthPlanStrings.sort();
    for (String plan : HealthPlanStrings){
        deDupedHPList.add(new SelectOption(plan, plan));
    }
    List<SelectOption> finalHPs = new List<SelectOption>();
    for (SelectOption o : deDupedHPList){
        finalHPs.add(o);
    }
    return finalHPs;
}

I am receiving a null pointer exception error that

"Argument 1 cannot be null."

The line that it directed me to is this one:

deDupedHPList.add(new SelectOption(plan, plan));

Could anyone direct me to why this error is coming up? It only happens sometimes for some customer portla users, as those are the user who will always have a contact associated with them.

Best Answer

The real problem lies in these lines

for (CustomObject__c snanas : sn){
    HealthPlanStrings.add(snanas.Service_Offering__r._Display_Name__c);
}

If the snanas.Service_Offering__r.Display_Name__c field is NULL, HealthPlanStrings is added with NULL.

So change those lines as below

for (CustomObject__c snanas : sn){
    if(snanas.Service_Offering__c != NULL && snanas.Service_Offering__r._Display_Name__c != NULL)
         HealthPlanStrings.add(snanas.Service_Offering__r.Display_Name__c);
}

Here i added snanas.Service_Offering__c != NULL before checking snanas.Service_Offering__r._Display_Name__c != NULL because it will not throw error if Service_Offering__c field is NULL.

Hope this helps.

Related Topic