function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mahmoud Coudsi 1Mahmoud Coudsi 1 

Execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.ReturnPercentWeightLossAt6WeeksMark: line 42, column 1

Hello,

High-level problem:

I'm trying to build a caculated filed that returns percent weight loss for patient accounts at 6 weeks mark. I did that through building a trigger and custom filed on the account object. Trigger works for some accounts and throw this error message (below) for other accounts.  

Error mesage return upon saving records:

I keep getting this error message upon saving editing/inserting new appointments (Child/Detail records) for persons account. 

Review all error messages below to correct your data.
Apex trigger ReturnPercentWeightLossAt6WeeksMark caused an unexpected exception, contact your administrator: ReturnPercentWeightLossAt6WeeksMark: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.ReturnPercentWeightLossAt6WeeksMark: line 42, column 1

(Please refer to the end of the page if you want a get a clearer idea of what I'm trying to accomplish by building this trigger)
 
Trigger ReturnPercentWeightLossAt6WeeksMark on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);

    //SOQL query that returns weight value at six weeks mark (Between 35 & 56; closer to 35) 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account account : [
            Select Id,Initial_Weight__c,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled') AND Days_since_first_appointment__c > 37 AND Days_since_first_appointment__c < 55  
                    Order by Scheduled_time__c asc
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Assigning account's inital weight value to variable
            Decimal InitialWeight = NULL;    
            
            //Declare a decimal variable to store latest weight value 
            Decimal SixWeeksWeight = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                SixWeeksWeight = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }
            
            if (account.Initial_Weight__c != NULL) {
                InitialWeight = account.initial_weight__c;
            }
                
            Decimal WeightLostAtSixWeeks = InitialWeight - SixWeeksWeight;
            Decimal PercentWeightLoss = (WeightLostAtSixWeeks/InitialWeight)*100; 
            
            //if (SixWeeksWeight == NULL) {SixWeeksWeight = 0;
            //   } else {
            
            AccountsToUpdate.add(new Account(
                Id = account.Id,
                Percent_weight_loss_at_6_weeks__c = PercentWeightLoss
            ));
                    
            //}
                         
        }   
        
        update AccountsToUpdate;
        
        }
      }
Here is some background information on what I'm trying to do with this code:

I have two objects; Patients (persons accounts, Master object) and Appointments (Detail object) and I'm trying to build a trigger (With SOQL query) that returns percent weight loss at 6 weeks mark per account on a custom field (Percent_weight_loss_at_6_weeks__c) that is built on the account (Persons account) object:
 
Object #1: (Appointments)
 
Appointment ID  Account ID,   Account Name,  Apt Date,   Weight....etc.
-----------------------------------------------------------------------------------------------
Apts_001112       001                John                 01/01/2017     160
Apts_001114       002                Nicole               11/05/2016      180
Apts_001113       001                John                 04/05/2017     175
Apts_001115       003                Mark                 05/05/2017      190   
Apts_001116       002                Nicole               12/15/2016      200
...
...
...
 
Object #2: (Accounts)
 
 ID,      Name         Percent Weight Loss at 6 weeks. (This the metric that I'm trying to return in the account object) 
----------------------------------------------------------------------------------------------
 001     John          3%
 002     Nicole        2%
 003     Mark          3%     
----------------------------------------------------------------------------------------------
P.S:

The trigger worked for patients (Person accounts) who have existing appointments at 6 weeks mark (between 35 - 56) but didn't work; threw the above error message ^, for patients who don't have appointment at 6 weeks mark.
HARSHIL U PARIKHHARSHIL U PARIKH
On line 28  and 31 change NULL to 0.00
Decimal InitialWeight = 0.00;
Decimal SixWeeksWeight = 0.00;
Apex doesn't understand how to add something into null but it understands how to add something into 0.00. It's that mysterious!!
Mahmoud Coudsi 1Mahmoud Coudsi 1
Hello Govind,

Thanks for the quick response! I tried to do the following, I got this error message back when I tried to insert an appointment record:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger ReturnPercentWeightLossAt6WeeksMark caused an unexpected exception, contact your administrator: ReturnPercentWeightLossAt6WeeksMark: execution of AfterInsert caused by: System.MathException: Divide by 0: Trigger.ReturnPercentWeightLossAt6WeeksMark: line 43, column 1
HARSHIL U PARIKHHARSHIL U PARIKH
It's look like at some point of a time InitialWeight soming as value zero.
Let's try re-writing line 43 as below,
If(InitialWeight > 0)
{
     Decimal PercentWeightLoss = (WeightLostAtSixWeeks/InitialWeight)*100; 
}
In addition, online 21 try removing LIMIT 1 since that would make loop runs only once in my opinion. I think how SOQL FOR loops are runs is that if your query fetches let's say 50 records then those records going to get assigned in account variable one by one until it reaches to the 50. But however, if you put the LIMIT 1 then SOQL by itself will return one record and FOR loop would run only once.