Skip to main content
Marlon Ocillos 님이 #Apex에 질문했습니다
Hi everyone,

I am having some problem with fetching a null value in a map. I am trying to update a related contact of an account when a field in the account is updated. Let's call it a LookupField__c because it's a lookup to a custom object.

I have this code:

Map<Id, Account> accMap = new Map<Id, Account>([query Accounts to put in map]);

contactList = [query Contacts to add in list];

for(Conact c : contactList) {

   if(accMap.get(c.AccountId).LookupField__c != null) {

      c.LookupField__c = accMap.get(c.AccountId).LookupField__c;

   } else {

      c.LookupField__c = null;

   }

}

It's working when I do it on the record. But when I do it on the test class, it returns an error 'Attempt to de-reference a null object'. I looked at the debug logs and the error occurs on the if statement. It does not check the condition rather it throws an error by just getting a null value from the field. Is their another way to check if the returned value of a map is null?
답변 5개
  1. 2015년 5월 7일 오후 2:59

    Sorry but I can't post the code here as it has some client data. I believe my test class is just fine like for example, I can get this in the Map

    accMap.get(c.AccountId).Id

    Meaning the key is present in the Map.

    But when I fetch the lookup field, which is not a required field so it can be left blank/null, the error occurs since the value returned is null.

    Thanks.

     
0/9000