0

When I use contains, I get Attempt to de-reference a null object:

for(Gear__c g : gears{
   if(toolsMap.get(g.Id).Status__c == 'Off' || toolsMap.get(g.Id).HelpText__c.contains('Hello there!')){
        System.debug('Here we go');
   }
}

When I change contains to ==, everything is fine. But I can have a few values in this field. How to write if logic to avoid the error?

  • 1
    You need to add a null check before accessing any field values. – Reshma Sep 18 '19 at 11:31
2

You are assuming that toolsMap.get(g.Id).HelpText__c always returns a value. This may not be true. So whenever it returns null, your current code will fail as you observe.

A refactored version of your code should look as below:

if(toolsMap.get(g.Id).Status__c == 'Off' 
     || (
            toolsMap.get(g.Id).HelpText__c != null 
                 && toolsMap.get(g.Id).HelpText__c.contains('Hello there!')
        ) {
    ...
}
| improve this answer | |

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.