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
Yoni LegacyYoni Legacy 

Error in running Insert Account List Item class

Hi Experts,

I am really new in apex class. I hope you can help me, I created a batch job to create/insert Account List records.
Link to my batch job question: http://salesforce.stackexchange.com/questions/132504/help-in-converting-my-apex-class-to-batch-job?noredirect=1#comment188702_132504

This Account List has Account List Item (RELATIONSHIP: Master-Detail)
Here is the code of my Account List Item
 
public with sharing class Eisai_InsertAccountListItem_cls{
    List<Account_List_Item_vod__c> toInsertAcctListItem = new List<Account_List_Item_vod__c>();
    List<Account_List_vod__c> allHOAccountList = new List<Account_List_vod__c>();
    List<Affiliation_vod__c> allAffiliationList = new List<Affiliation_vod__c>();
    List<Affiliation_vod__c> allChildAffList = new List<Affiliation_vod__c>();
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>();
    Set<String> affToAcctValSet = new Set<String>();
    Set<String> allHOAccountListName = new Set<String>();

    public Eisai_InsertAccountListItem_cls(){


        for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                                WHERE Parent_vod__c = false
                                                                                AND OwnerId IN:getActiveUsers()])
        {
            if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
                  allChildAffList.add(allAffiliationList);
                affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
            }
        }

        for (Account_List_vod__c allHOAccountListQuery : [SELECT Id, OwnerId, Name, Name_Substring__c FROM Account_List_vod__c 
                                                                                                      WHERE Name_Substring__c IN :affToAcctValSet]){
            allHOAccountList.add(allHOAccountListQuery);
        }

            for(Affiliation_vod__c affRec: allChildAffList)
                for(Account_List_vod__c allHOAccountListInsert : allHOAccountList){
                    if(allHOAccountListInsert.Name_Substring__c.equals(affRec.To_Account_Value__c)){ 
                  //     &&  allAffiliationList.OwnerId.equals(allHOAccountListInsert.OwnerId)){
                        Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c(
                              Account_List_vod__c = allHOAccountListInsert.Id,
                              Account_vod__c = affRec.From_Account_vod__c
                        );
                        toInsertAcctListItem.add(AccListItem);
                     }
                }

    Database.SaveResult[] srList = Database.insert(toInsertAcctListItem, false);

    for (Database.SaveResult sr: srList){
        if(sr.isSuccess()){
            System.debug('Inserted Account List Item Id: ' + sr.getId());
        } else {
            for(Database.Error err : sr.getErrors()){
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
        }
               }
    }


}//end of Constructor

    public Set<Id> getActiveUsers(){

        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%'
                                             OR Profile_Name_vod__c LIKE '%Eisai_System%') 
                                      AND IsActive = TRUE]); 

        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}//end of Class

I am receiving an error message like this below:

User-added image

Note: There are many child affiliation record (Parent = False) with 1 To_Account_vod_value(Account Name) and but different From_Account_vod (Person Accounts) So I tried to limit to get only 1 record (To_Account_vod_value) by this line of codes:
 
for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                        WHERE Parent_vod__c = false
                                                                        AND OwnerId IN:getActiveUsers()])
{
    if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
          allChildAffList.add(allAffiliationList);
        affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
    }
}

Thanks 
Marion
Rajnish Bishnoi 13Rajnish Bishnoi 13
you can pass the size in Database.executeBatch() like how many record should go to process for single batch...
reduce that size and error will be gone.
Yoni LegacyYoni Legacy
Hi Rajnish,

Are you saying to convert it to Batch job? if yes, hmmm i'm just really new in apex coding. but if you have sample I can try it.

Marion
Rajnish Bishnoi 13Rajnish Bishnoi 13
i was hoping that you are using batch jobs, but if you are not using then you need to use that.
Below is the explaination of batcheable and schedulable class and how to call them, hope it will help you.

Batch Apex in Salesforce
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
 
Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.
 
Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}
 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}
 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
 
Example of Batch Apex Class: 
 
Batch Schedule Class
global class batchContactUpdate implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id, FirstName,LastName FROM Contact';
        return Database.getQueryLocator(query);
    }
  
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact a : scope)
         {
             a.FirstName=a.FirstName+'FirstName is Updated';
             a.LastName = a.LastName +'LastName is updated';         
         }
         update scope;
    } 
    global void finish(Database.BatchableContext BC)
    {
    }
}
Schedule Class
-----------------------
 
global class BatchScheduleUpdate implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
        
        // We now call the batch class to be scheduled
        BatchContactUpdate b = new BatchContactUpdate ();
        
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
    
}
Schedule from Developer Console
-------------------------------------------------
BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
String sch='0 5 2 * * ?';
//System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
System.schedule('Batch Schedule', sch , batchSch);

Please accept my solution as Best Answer if my reply was helpful.
Yoni LegacyYoni Legacy
Hi,

I tweaked my code above but I'm getting different error.
 
public with sharing class Eisai_InsertAccountListItem_cls{
    List<Account_List_Item_vod__c> toInsertAcctListItem = new  List<Account_List_Item_vod__c>();
    List<Affiliation_vod__c> allAffiliationList = new List<Affiliation_vod__c>();
    List<Affiliation_vod__c> allChildAffList = new List<Affiliation_vod__c>();
    Map<String,Account_List_vod__c> nameToAcctListMap = new Map<String,Account_List_vod__c>();
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>();
    Set<String> affToAcctValSet = new Set<String>();
    Set<String> allHOAccountListName = new Set<String>();
    Integer totalRecordsInserted = 0, totalRecordsFailed = 0;
    
    public Eisai_InsertAccountListItem_cls(){
		
        allAffiliationList = [SELECT ID, OwnerId, Name, From_Account_vod__c, Account_List_Unique__c, To_Account_Value__c 
                              													FROM Affiliation_vod__c 
																				WHERE Parent_vod__c = false
                              													AND To_Account_Value__c != Null
                                                      							AND From_Account_RecType__c = 'Professional_vod'
																				AND OwnerId IN:getActiveUsers()];
		
		for (Affiliation_vod__c AffiliationList: allAffiliationList)
		{
                allChildAffList.add(AffiliationList);
                affToAcctValSet.add(AffiliationList.To_Account_Value__c);
		}
    
        for (Account_List_vod__c allAcctListQuery : [SELECT Id, OwnerId, Name, Name_Substring__c, Name_Populate_Unique_Owner__c 
                                                          							FROM Account_List_vod__c 
                                                          							WHERE Name_Substring__c IN :affToAcctValSet]){
            nameToAcctListMap.put(allAcctListQuery.Name_Substring__c, allAcctListQuery);
        }
        
        System.debug('Account List Map count: ' + nameToAcctListMap.size());
    
        for(Affiliation_vod__c affRec: allChildAffList){
				Account_List_vod__c acctListRec = nameToAcctListMap.get(affRec.To_Account_Value__c);
                        
            if(affRec.Account_List_Unique__c.equals(acctListRec.Name_Populate_Unique_Owner__c)){               
						Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c(
							  Account_List_vod__c = acctListRec.Id,
							  Account_vod__c = affRec.From_Account_vod__c
						);
						toInsertAcctListItem.add(AccListItem);
			}
        }
	
    	for(Database.SaveResult result: Database.insert(toInsertAcctListItem,false)) {
            if(result.isSuccess()) {
                totalRecordsInserted++;
            } else {
                totalRecordsFailed++;
            }
        }
        
    	System.debug('Records successfully inserted: ' + totalRecordsInserted);
        System.debug('Records failed insertion: ' + totalRecordsFailed);
    
}//end of Constructor

    public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%'
                                             OR Profile_Name_vod__c LIKE '%Eisai_System%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}//end of Class

Here is the error message:

User-added image

I am trying to map the query result of Account List record. It's saying that I am referrencing null object.

Anythougts?

Thanks
Marion
Rajnish Bishnoi 13Rajnish Bishnoi 13
It means you are gettin null value in 
 Account_List_vod__c acctListRec =nameToAcctListMap.get(affRec.To_Account_Value__c);
means to say that your map nameToAcctListMap having the null value for affRec.To_Account_Value__c