[SalesForce] Execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object

I am new to coding. Could anyone please help me here. when this trigger is executing after inserting the record in Account using Anonymous Window i am getting the below error:-

Line: 2, Column: 1 System.DmlException: Insert failed. First exception
on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,
ChangeRecordTypeID: execution of BeforeInsert caused by:
System.NullPointerException: Attempt to de-reference a null object
Trigger.ChangeRecordTypeID: line 22, column 1: []

trigger ChangeRecordTypeID on Account (before insert) {

    Profile p = [SELECT Id FROM Profile WHERE Name='Data Migration']; 


    Set<String> oldRecordTypeNameSet = new Set<String>();

   // List<String> oldRecordTypeNameList;
        for(Account acc : Trigger.New){

           oldRecordTypeNameSet.add(string.valueOf(RecordTypeSetting__c.getvalues(acc.Old_Record_Type_Id__c).Record_Type_Name__c));
       }
        Map<String,Id> GetNameFromOldId = new Map<String,Id>();
        for(RecordType rt : [SELECT Id,RecordType.developerName FROM RecordType where SobjectType = 'Account' And RecordType.developerName =: oldRecordTypeNameSet])
        {
          GetNameFromOldId.put(rt.developername,rt.Id);
        }
    if(p.Id == UserInfo.getProfileId()){
        for(Account acc : Trigger.New){   

             RecordTypeSetting__c rts = RecordTypeSetting__c.getInstance(acc.RecordTypeID);
             acc.RecordTypeId = GetNameFromOldId.get(rts.Record_Type_Name__c);

        }   
    } 
 }

Best Answer

The reason you are getting a NullPointerException here is because rts is null. Your code makes an assumption that the Id value of acc.RecordTypeId will be the name of an instance of your RecordTypeSetting__c custom setting. In this case, that assumption appears flawed. The most basic fix would be to add a null check on rts:

RecordTypeSetting__c rts = RecordTypeSetting__c.getInstance(acc.RecordTypeID);
if (rts != null)
{
    acc.RecordTypeId = GetNameFromOldId.get(rts.Record_Type_Name__c);
}
Related Topic