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
@GM@GM 

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

trigger updateCount on Student__c (after insert, after delete)
{
Integer clist=0;
if(Trigger.isAfter && Trigger.isInsert)
{
for (Student__c stent : Trigger.new)
{
Id cid = stent.Class__c;
clist = [Select Count() FROM Student__c where Class__c =: cid ];
if(stent.Class__r.My_Count__c == null)
{
stent.addError('null');
}
else
{
stent.Class__r.My_Count__c = clist + 1;
}
}
}
else if(Trigger.isAfter && Trigger.isDelete)
{
for (Student__c stent : Trigger.old)
{
Id cid = stent.Class__c;
clist = [Select Count() FROM Student__c where Class__c =: cid ];
stent.Class__r.My_Count__c = clist - 1;
}
}

}


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

Best Answer chosen by Admin (Salesforce Developers) 
Dhaval PanchalDhaval Panchal

Below is not possible

stent.Class__r.My_Count__c = clist + 1;

You have to fetch record using query if you want to update relational fields.

And also in trigger you cannot get value for relational fields. You need to query those fields.

All Answers

Dhaval PanchalDhaval Panchal

Below is not possible

stent.Class__r.My_Count__c = clist + 1;

You have to fetch record using query if you want to update relational fields.

And also in trigger you cannot get value for relational fields. You need to query those fields.

This was selected as the best answer
@GM@GM
Hi Dapanchal,

Thanks for the information. but can you tell me that how to update the relationship field after fetching those relationship fields from SOQL.?