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
SFDC16SFDC16 

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

hello,

I am getting an error for below code 
System.NullPointerException: Attempt to de-reference a null object


  Account[] acc1=[Select id,name from account];
       Case ca=new Case();
       ca.Status='New';
       ca.Origin='Phone';
       ca.Account.name=acc1[0].name; // --------> error line
       ca.Subject='hello';       
       insert ca;
       system.debug('Account Name'+ca);
      
Best Answer chosen by SFDC16
Naren9Naren9
Change it to
 ca.AccountId=acc1[0].Id;

All Answers

Naren9Naren9
Change it to
 ca.AccountId=acc1[0].Id;
This was selected as the best answer
SFDC16SFDC16
now I am getting below error. Expression must be a list type: Account
Naren9Naren9
to me it is working with out any error.
Try by changing to
 List<Account> acc1=[Select id,name from account];
 
SFDC16SFDC16
Thank you for your response, It's working now.