+ Start a Discussion
SandrineSandrine 

Check for map.containsKey is not firing

Hello,

I have written a code below the null pointer exception is fired to log mesages in a custom object but it is not entering the loop, what can be possible reason.
 
Map<Id, RecordType> rtMap = rtTemp.get(String.valueOf(Account.SObjectType));

	String rtTemp = (String) obj.get(RT_ID);

	if (!rtMap.containsKey(rtTemp)){  //not entering this loop
		logic to put a log in custom object
	}
	
	String rtDName = rtMap.get(rtTemp).DeveloperName; //null pointer

 
Best Answer chosen by Sandrine
AnudeepAnudeep (Salesforce Developers) 
Hi Sandrine, 

I suspect rtTemp is returning a null value

I recommend adding debug statements to the code to understand the underlying issue
 
Map<Id, RecordType> rtMap = rtTemp.get(String.valueOf(Account.SObjectType));
System.debug('check if rtMap is populated' + rtMap); 

	String rtTemp = (String) obj.get(RT_ID);

    System.debug('Check if rtTemp has any value' + rtTemp); 

	if (!rtMap.containsKey(rtTemp)){  //not entering this loop
		logic to put a log in custom object
	}
	
	String rtDName = rtMap.get(rtTemp).DeveloperName; //null pointer

Also, you can use isEmpty() method of map class to check if a map is null to avoid null pointer exception

Let me know if it helps