I am trying to create a Map of Account Record Types that any method in my class can reference and only the first call will need to populate it. Since it's populated by a SOQL query, I want to limit that necessity to only once.

I'm attempting to do this with a getter, but I'm not committed to that if there is a better design.

When I attempt the following in Execute Anonymous, it throws "System.NullPointerException: Attempt to de-reference a null object" for the accountRecordTypes.isEmpty().

public static Map<String, String> accountRecordTypes {
        get {
            if (accountRecordTypes.isEmpty()){
                accountRecordTypes = new Map<String, String>();
                //Create a map between the Record Type Name and Id for easy retrieval in both Sandbox and Production
                List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Account' and isActive=true];

                for(RecordType rt: rtypes) accountRecordTypes.put(rt.Name,rt.Id);
            return accountRecordTypes;

You need to add a null check to your guard condition.

 if (accountRecordTypes == null || accountRecordTypes.isEmpty()) {

The corresponding member that automagically exists behind the property won't be initialised until you call accountRecordTypes = new Map<String, String>();. So the original call to .isEmpty() would have been on null.

As Jesse Altman commented, the null check alone is probably preferable here. If there are no RecordType records that match the SOQL query you don't want to be running the query code again every time the property is called.

  • 2
    Beat me to it by a few seconds, but this is the right answer. You are calling isEmpty on an instance that has never been instantiated. I would also go as far as removing the isEmpty() call all together. If your SOQL query returns an empty list for some reason, every time this property is called it will re-query it over and over again always returning the same result of nothing. That isn't efficient and will each up SOQL queries against your limit. – Jesse Altman Jun 3 '14 at 22:02

Change this:

 if (accountRecordTypes.isEmpty()){


 if (accountRecordTypes == null){

When using a method of one object, you need to check whether the object is existing (object != null).

But in your case, I think you can use the following code to get the Record Type Id that is better.

Schema.DescribeSObjectResult d = Schema.SObjectType.Account;
Map<String, Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();
Schema.RecordTypeInfo rtByName =  rtMapByName.get('name');
if(rtByName != null) {
    Id reocrdId = (rtByName.isAvailable()) ? rtByName.getRecordTypeId() : null;

You can only return 100 RecordTypeInfo objects per Apex request.

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.