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

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

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

System.NullPointerException: Attempt to de-reference a null object is very common error in apex class.  It occurs when your variable (sobject, list, set or any other data type) is not initialized (allocated memory). In order to use the non primitive data type in the code we need to initialize the memory first. If we don’t do that it may result in Attempt to de-reference a null object error. This error may occur in Apex classes, Visualforce pages with Apex controller, Test classes, Apex Triggers.

attempt to de-reference a null object

For Example if I use like this:

Account acc;
acc.Name = 'sfdcpoint';

It will result in attempt to de-reference a null object error.

We should use it like this:

Account acc = new Account();
acc.Name = 'sfdcpoint';

When we use list or set then also we need to allocate memory to list or set like this

List<Account> accList = new List<Account>();
Set<String> strSet= new Set<String>();

Same way this error can occur when we get null result from map and we try to use it in our code. For example we have accountMap with Id as key and Account as value:

Account accRecord = accountIdAccountMap.get(accId);
System.debug('*****accRecord.Name'+accRecord.Name);

Above code will also result in error. Here in above code accountIdAccountMap or  accRecord can be null. So we should do null check before using it like this.

if(accountIdAccountMap != null){
    Account accRecord = accountIdAccountMap.get(accId);
    if(accRecord != null){
        System.debug('*****accRecord.Name'+accRecord.Name);
    }
}

It is also very good practice to use isEmpty() method like this:

if(!accList.isEmpty()){
     //Do your dml or other operations here
}

As a best practice we should always do exception handling in our code like this

try{
    //Code here
}catch(Exception e){
    //Handle exception here
}

If you get System.NullPointerException. Its advisable to use System.debug to debug line of code which is resulting in this error and then fix it.

We should also use try catch block and exception handling mechanism to handle any unexpected error like this. For more details about exception please refer exception handling

Here are salesforce official link for same error

Error in Apex code trigger

Error in Salesforce CPQ

For salesforc lightning interview questions refer to below link salesforce lightning

Happy coding 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/system-nullpointerexception-attempt-to-de-reference-a-null-object/

4 comments

Skip to comment form

    • rejeesh on April 27, 2020 at 2:07 am
    • Reply

    trigger ExpensiveCompetitor on Opportunity (before insert,before update) {
    for(Opportunity opp : Trigger.new){
    List Prices = new List();
    Prices.add(opp.Competitor_1_Price__c);
    Prices.add(opp.Competitor_2_Price__c);
    Prices.add(opp.Competitor_3_Price__c);
    List Expensive = new List();
    Expensive.add(opp.Competitor_1__c);
    Expensive.add(opp.Competitor_2__c);
    Expensive.add(opp.Competitor_3__c);
    Decimal greatestprice;
    Integer greatestpriceposition;
    for(Integer i=0;i>prices.Size();i++){
    Decimal currentprice = Prices.get(i);
    if(greatestprice == null|| currentprice > greatestprice){
    greatestprice = currentprice;
    greatestpriceposition=i;
    }
    }
    opp.Expensive_Competitor__c = Expensive.get(greatestpriceposition);
    }
    }
    I tried to update Expensive_Competitor__c to highest number but it shows a null pointer error
    ExpensiveCompetitor: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.ExpensiveCompetitor: line 21, column 1

    1. Hello
      Can you please explain what you are trying to do and which line from above code is 21st line which is giving error

    • satya on January 2, 2021 at 7:01 pm
    • Reply

    public class getObjectNames {
    public list options{get;set;}
    public string selected {get;set;}
    public list FieldNames{get;set;}
    public Map objMap;
    public getObjectNames(){
    options = new List();
    Map objMap = Schema.getGlobalDescribe();
    // set objectNames = objMap.keySet();
    List objectNames = new List(objMap.keySet());
    objectNames.sort();
    for(String s:objectNames){
    Selectoption op = new Selectoption(s,s);
    options.add(op);
    }
    }
    public void getFieldNames(){
    Schema.SObjectType objectToken = objMap.get(selected);
    Schema.DescribeSObjectResult objectResult = objectToken.getDescribe();
    Map fieldMap = objectResult.fields.getMap();
    FieldNames = new List();
    for(String f : fieldMap.keyset()){
    SelectOption op= new SelectOption(f,f);
    FieldNames.add(op);
    }
    }
    }
    i am getting error:
    System.NullPointerException: Attempt to de-reference a null object
    Error is in expression ‘{!getFieldNames}’ in page getobjectnames: Class.getObjectNames.getFieldNames: line 18, column 1
    Class.getObjectNames.getFieldNames: line 18, column 1
    how to resolve

    • Chris Meeuwen on January 22, 2021 at 10:21 pm
    • Reply

    // Apex Batch Class: AccountRecycleCheck
    // Written by: Chris Meeuwen
    //——————————————————————————————//
    // Use Case 1 Scope:
    // =================
    // 1. If an Account that is not active, and has no open opportunities or Tasks.
    // Then unassign account in 30 days.
    //
    //
    //
    // Use Case 2 Scope:
    // =================
    // 1. If a recycled account is re-assigned to a sales rep and has no closed won opportunities
    // or open tasks assign acount to No Sales Contact in 90 days
    //
    //
    // Related MetaData:
    //
    // 1. Hidden Account field: No Open Opties Assign to NSC in 30 days
    // 2. Hidden Account field: Ops Status Trigger
    // 3. Hidden Account field: Recycled Account
    // 4. Hidden Account field: Last Open Activity Or Oppty Date
    //——————————————————————————————//

    global class AccountRecycleCheck implements Database.Batchable {

    global Database.QueryLocator start(Database.BatchableContext BC) {

    // collect the batches of records or objects to be passed to execute
    String query = ‘SELECT Id, OwnerId, Recycled_Count__c, Customer_Status__c, No_Open_Opties_Assign_to_NSC_in_30_days__c, Last_Open_Activity_Or_Oppty_Date__c, Recycled_Account_Assign_to_NSC_in_90_Day__c FROM Account Where Customer_Status__c != \’Cancelled\’ OR Customer_Status__c != \’Never Active\”;
    return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List NonCustomerAccounts) {

    // Account List For Loop
    // ———————
    for(Account A1 : NonCustomerAccounts){

    if(A1.Customer_Status__c == ‘Cancelled’ || A1.Customer_Status__c == ‘Never Active’) {

    // Get Related Opportunities And Task Records
    // ——————————————
    List GetOpenTasks = [Select Id, Status From Task
    Where accountId = :A1.Id
    AND Status != ‘Completed’ Limit 1];

    List GetOpenOpties = [Select Id, StageName From Opportunity
    Where accountId = :A1.Id
    AND StageName != ‘Closed Lost’ Limit 1];

    // Use Case 1 Loop: Accounts being recycled the first time
    // If account is cancelled or Never Active and has no open
    // opportunities that are closed won or tasks
    // ——————————————————-
    if(!GetOpenTasks.IsEmpty() || !GetOpenOpties.IsEmpty()){

    System.debug(‘Account: ‘ + A1.Id + ‘ – Has open opportunities Or tasks.’);

    Try{
    A1.No_Open_Opties_Assign_to_NSC_in_30_days__c = False;
    A1.Last_Open_Activity_Or_Oppty_Date__c = Null;
    A1.Recycled_Account_Assign_to_NSC_in_90_Day__c = False;

    Update A1;
    }
    Catch(DmlException e){
    System.debug(‘The following error has occured: ‘ + e.getMessage());
    }

    }
    Else {
    System.debug(‘Account: ‘ + A1.Id + ‘ – Has no open opportunities Or tasks.’);

    // 30 Day Initial Recycle Trigger Check
    // If no open opptys or tasks set
    // checkbox for 30 day reassignment and
    // the last open activity date
    // ————————————
    If(A1.No_Open_Opties_Assign_to_NSC_in_30_days__c != True && A1.Recycled_Count__c == 0){

    Try{
    A1.No_Open_Opties_Assign_to_NSC_in_30_days__c = True;
    A1.Last_Open_Activity_Or_Oppty_Date__c = Date.today();

    update A1;
    }
    Catch(DmlException e){
    System.debug(‘The following error has occured: ‘ + e.getMessage());
    }
    }
    Else{
    System.debug(‘Initial 30 Day Recycle Process already performed on account or account does not meet criteria: ‘ + A1.Id);
    }

    // 90 Recycled Account Trigger Check
    // If no open opptys or tasks set
    // checkbox for 90 day reassignment and
    // the last open activity date
    // ————————————
    If(A1.Recycled_Account_Assign_to_NSC_in_90_Day__c != True && A1.Recycled_Count__c >= 1){

    Try{
    A1.Recycled_Account_Assign_to_NSC_in_90_Day__c = True;
    A1.Last_Open_Activity_Or_Oppty_Date__c = Date.today();

    Update A1;
    }
    Catch(DmlException e){
    System.debug(‘The following error has occured: ‘ + e.getMessage());
    }

    }
    Else{
    System.debug(’90 Day Recycle Process already performed on account or account does not meet criteria: ‘ + A1.Id);
    }
    }

    // No Open Opties Assign to NSC in 30 Days is Set to True:
    // If Account has been marked for 30 day assignment
    // ——————————————————
    if(A1.No_Open_Opties_Assign_to_NSC_in_30_days__c == True && A1.Recycled_Account_Assign_to_NSC_in_90_Day__c == False){

    // Calling Method to evaluate 30 Recycle
    // ————————————-
    Try{
    NoOpenOptyorTasksAssignNSCin30Days(A1.Id);
    }
    Catch(DmlException e){
    System.debug(‘An Error has occurred: ‘ + e.getMessage());
    }
    }
    Else{
    System.debug(‘Account: ‘ + A1.Id + ‘Does not meet 30 day Recycling Conditions – End Loop 2’);
    }

    // Recycled Account Assign to NSC in 90 Day is Set to True
    // ——————————————————-
    if(A1.No_Open_Opties_Assign_to_NSC_in_30_days__c == False && A1.Recycled_Account_Assign_to_NSC_in_90_Day__c == True){

    // Get ID of NSC User
    // ——————
    List NSCUserID = [Select Id, FirstName, LastName From User Where LastName = ‘No Sales Contact’];

    for(User NSC : NSCUserID){

    if(A1.OwnerId != NSC.Id){

    System.debug(A1.Id + ‘ is a recycled account – Check 90 Day Reassignment Logic’);

    // Calling Method to evaluate 90 Recycle
    // ————————————-
    Try{
    RecycledAccountAssignNSCin90Days(A1.Id);
    }
    Catch(DmlException e){
    System.debug(‘An Error has Occured: ‘ + e.getMessage());
    }

    }
    Else{
    System.debug(‘Account ‘ + A1.Id + ‘ is owned by NSC Still, will evaluate 90 Recycle once re-assigned’);
    }

    }

    }
    Else{
    System.debug(‘Account: ‘ + A1.Id + ‘ Does not meet 90 day Recycling Conditions – End Loop 3’);
    }

    // If Account has already been assigned to NSC – Has not been assigned to a sales rep
    // ———————————————————————————-
    List GetNSCUserID = [Select Id, FirstName, LastName From User Where LastName = ‘No Sales Contact’];

    for(User IsUserOwnedByNSC : GetNSCUserID){

    if((A1.OwnerId == IsUserOwnedByNSC.id && A1.No_Open_Opties_Assign_to_NSC_in_30_days__c == True) ||
    (A1.OwnerId == IsUserOwnedByNSC.id && A1.Recycled_Account_Assign_to_NSC_in_90_Day__c == True)){

    system.debug(‘Account: ‘ + A1.Id + ‘ owned by NSC Resetting Recycle Logic’);

    Try{
    A1.No_Open_Opties_Assign_to_NSC_in_30_days__c = False;
    A1.Recycled_Account_Assign_to_NSC_in_90_Day__c = False;
    A1.Last_Open_Activity_Or_Oppty_Date__c = Null;

    Update A1;
    }
    Catch(DmlException e){
    System.debug(‘The following error has occured: ‘ + e.getMessage());
    }

    }
    Else{
    system.debug(‘Account not owned by No Sales Contact!’);
    }

    }

    }
    Else{

    System.debug(‘Account is not Cancelled or Never Active’);

    }

    }

    }

    global void finish(Database.BatchableContext BC) {

    //system.debug(‘ Records Processed ‘);
    }

    // Method to Check if no open activities or closed won opportunities for 30 Days
    // —————————————————————————–
    public static void NoOpenOptyorTasksAssignNSCin30Days(String AcId30Day){

    // Get Id Of NSC User
    // ——————
    List GetNSCUserID = [Select Id, FirstName, LastName From User Where LastName = ‘No Sales Contact’];

    // Creates a List containing and the Account being processed
    // ———————————————————
    List GetUseCase1Account = [Select ID, Recycled_Count__c, Last_Open_Activity_Or_Oppty_Date__c From Account Where Id = :AcId30Day];

    for(Account UseCase1Account : GetUseCase1Account){

    // Calculate Difference in Days for the Last Open Activity or Closed Won Opportunity Date
    // ————————————————————————————–
    Integer DateDifference = (UseCase1Account.Last_Open_Activity_Or_Oppty_Date__c).daysBetween(Date.valueOf(System.today()));

    system.debug(‘Account: ‘ + UseCase1Account.Id + ‘ Days since last open activity or closed won opportunity: ‘ + DateDifference);

    if(DateDifference >= 30){

    System.debug(‘No Open Activities or Opportunities. Assigning to NSC for account: ‘ + UseCase1Account.Id);

    for(User UIDNSC : GetNSCUserID){

    System.debug(‘Assigning account: ‘ + UseCase1Account.id + ‘ to NSC and adding to Recycle Count’);

    Try{
    UseCase1Account.OwnerId = UIDNSC.id;
    UseCase1Account.Recycled_Count__c = UseCase1Account.Recycled_Count__c + 1;
    UseCase1Account.No_Open_Opties_Assign_to_NSC_in_30_days__c = False;
    UseCase1Account.Recycled_Account_Assign_to_NSC_in_90_Day__c = True;

    Update UseCase1Account;
    }
    Catch(DmlException e){System.debug(‘The following error has occured: ‘ + e.getMessage());}
    }

    }
    Else{

    system.debug(‘Use Case 1: 30 Days has not passed for account: ‘ + UseCase1Account.Id);

    }

    }

    }

    // Method to Check if no Open Activities or closed won opportunities for 90 Days
    // —————————————————————————–
    public static void RecycledAccountAssignNSCin90Days(String AcId90Day){

    // Get Id Of NSC User
    // ——————
    List GetNSCUserID2 = [Select Id, FirstName, LastName From User Where LastName = ‘No Sales Contact’];

    List GetUseCase2Account = [Select ID, Recycled_Count__c, Last_Open_Activity_Or_Oppty_Date__c From Account Where Id = :AcId90Day];

    for(Account UseCase2Account : GetUseCase2Account){

    Integer DateDifference2 = (UseCase2Account.Last_Open_Activity_Or_Oppty_Date__c).daysBetween(Date.valueOf(System.today()));

    system.debug(‘Account: ‘ + UseCase2Account.Id + ‘ Days since last open activity or closed won opportunity: ‘ + DateDifference2);

    if(DateDifference2 >= 90){

    for(User UIDNSC2 : GetNSCUserID2){

    System.debug(‘Assigning account: ‘ + UseCase2Account.id + ‘ to NSC and adding to Recycle Count’);

    Try{
    UseCase2Account.OwnerId = UIDNSC2.id;
    UseCase2Account.Recycled_Count__c = UseCase2Account.Recycled_Count__c + 1;
    UseCase2Account.No_Open_Opties_Assign_to_NSC_in_30_days__c = False;
    UseCase2Account.Recycled_Account_Assign_to_NSC_in_90_Day__c = False;
    UseCase2Account.Last_Open_Activity_Or_Oppty_Date__c = Null;

    Update UseCase2Account;
    }
    Catch(DmlException e){
    System.debug(‘The following error has occured: ‘ + e.getMessage());
    }
    }

    }
    Else{
    system.debug(‘Use Case 2: 90 Days has not passed for account: ‘ + UseCase2Account.Id);
    }

    }

    }

    }

    Exception / Error in debug log:

    14:07:47.0 (25550194)|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

    Class.AccountRecycleCheck.NoOpenOptyorTasksAssignNSCin30Days: line 235, column 1
    Class.AccountRecycleCheck.execute: line 133, column 1
    14:07:47.0 (53218289)|CODE_UNIT_FINISHED|AccountRecycleCheck
    14:07:47.0 (53232062)|EXECUTION_FINISHED

Leave a Reply

Your email address will not be published.