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
  • 1
    You need to add a null check before accessing any field values.
    – Reshma
    Sep 18, 2019 at 11:31

1 Answer 1

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!')
        ) {
    ...
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .