I am iterating through an array of a List of Maps and want to run an if function whenever an item from the list meets a condition.

The problem I am currently facing is Salesforce producing the following error:

System.NullPointerException: Attempt to de-reference a null object

Here's the code with some more explanations:

    for ( Integer i=1; i<allRows.size(); i++ ){
          //this system.debug is to iterate over all lists, extract the values
          //under the 'Names' header and display them in debug (IT WORKS)
          String namesRow = allRows[i].get('Names');
          //The below debug also produces the correct values          
          system.debug('namesRow is ' +namesRow);
          //When the below function is active I am getting the NullPointerException Error
          if (namesRow.contains('Andrew')){
            system.debug('this name is in the database!');



1 Answer 1


You can check if a variable is null before you de-reference it:

if (myVariable != null && myVariable.contains('<substring>'))
    // do stuff

When you call myVariable.someMethod(...), the system tries to de-reference the value of myVariable. If it is null, you will get this exception. Any time you have a value which could possibly be null, you should protect yourself with null checks like the above.

Note that if statements perform short-circuit evaluation, and that is why your variable would never get de-referenced using the above pattern. It would be essentially the same as:

if (myVariable != null)
    if (myVariable.contains('<substring>')
        // do stuff
  • I am still getting the same error when using your if class, for your reference, that's how it looks: if (namesRow != null && namesRow.contains('Andrew')){ system.debug('this name is in the list!'); } Jun 16, 2017 at 22:18
  • @KamilMieczakowski Did you replace if (namesRow.contains('Andrew')) entirely?
    – Adrian Larson
    Jun 16, 2017 at 22:20
  • yes, I also pasted it in the above comment for your evaluation Jun 16, 2017 at 22:22
  • @KamilMieczakowski Then you are getting the error on a different line. Double check your stack trace.
    – Adrian Larson
    Jun 16, 2017 at 22:23
  • Could it be the fact that I am getting the relevant string from a list of maps? that's what it is: String investmentsRow = allRows[i].get('Names'); It works when I debug it... Jun 16, 2017 at 22:25

You must log in to answer this question.

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