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
Monin SavantMonin Savant 

Get a list of accounts in which there is a closed opportunity

I try check if opportunity exists.
I know for sure that yes and it goes into a loop, but then it throws an error 'System.NullPointerException'. Why?
@AuraEnabled(cacheable=true)
    public static List<Account> getRecById(String recId) {
        List<Account> listofaccts = [SELECT Total_Opportunity_Amount__c, Name, (SELECT Id, Name, Amount, CreatedDate, CloseDate FROM Opportunities WHERE StageName = 'Closed Won' ) FROM Account WHERE id=:recId ];
         List<Account> resultAcc;
        for(Account acc : listofaccts){
              if(!acc.Opportunities.isEmpty())
              {
                  resultAcc.add(acc);
              }
           }
         return resultAcc;
    }
Thanks in advance.
 
Best Answer chosen by Monin Savant
Aneesh AllumallaAneesh Allumalla

Hi ,

Null pointer occurs when you are trying to use a list which has now values in it or when a list is not initialized.
In your case, you have not initialized List <Account> resultAcc; 

So replace it with List <Account> resultAcc= new List<Account>();
Also as a best practice, check listofaccts is not empty before using it in for loop.
Hope this helps.

Please mark this as best answer if you find it helpful.

All Answers

Aneesh AllumallaAneesh Allumalla

Hi ,

Null pointer occurs when you are trying to use a list which has now values in it or when a list is not initialized.
In your case, you have not initialized List <Account> resultAcc; 

So replace it with List <Account> resultAcc= new List<Account>();
Also as a best practice, check listofaccts is not empty before using it in for loop.
Hope this helps.

Please mark this as best answer if you find it helpful.

This was selected as the best answer
mukesh guptamukesh gupta
Hi,

Please use below code:-
 
@AuraEnabled(cacheable=true)
    public static List<Account> getRecById(String recId) {
        List<Account> listofaccts = [SELECT Total_Opportunity_Amount__c, Name, (SELECT Id, Name, Amount, CreatedDate, CloseDate FROM Opportunities WHERE StageName = 'Closed Won' ) FROM Account WHERE id=:recId ];
         List<Account> resultAcc = new List<Account>();
        for(Account acc : listofaccts){
              if(!acc.Opportunities.isEmpty())
              {
                  resultAcc.add(acc);
              }
           }
         return resultAcc;
    }

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh