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
Arjun y 7Arjun y 7 

Need to pass apex class values to batch class

Hi All,

I need to return the values from apex class to batch class. The below code throws constructor not defined. Can any one let me know how to pass list of inserted accounts to batch class.
 
public with sharing class CalloutBatchApex implements Database.Batchable<Integer>, Database.AllowCallouts {
    public Iterable<String> start(Database.BatchableContext BC) {
        return new List<Integer> { 1, 2, 3 };
    }
 
    public void execute(Database.BatchableContext info, List<integer> iteration) {
        // Make the callout to the web service and import the records to Salesforce for the iteration.
       String responseStrng = response.getBody();
        insertAccountMethod.methodone(responseStrng);
    }
 
    public void finish(Database.BatchableContext info) {}
}

//Calling Apex class here

public class insertAccountMethod{
   List<Account> accList = new List<Account>();
         public methodone(String responseStrng){
         //my code here
         I need to return the above accList to batch class.I have tried with the below line
          
         CalloutBatchApex c = new CalloutBatchApex();
         DataBase.execute(c,1);

        }
}

Thanks
​Arjun
Alexander TsitsuraAlexander Tsitsura
Hello,

To execute Batch you need use Database.executeBatch instead of Database.execute method

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you.

Thanks,
Alex
Arjun y 7Arjun y 7
Hi Alex,

I tried with the above method also. I am receiving Constructor Not Defined error.

Thanks
Alexander TsitsuraAlexander Tsitsura
At first, you need to create constructor in batch class
public with sharing class CalloutBatchApex implements Database.Batchable<Integer>, Database.AllowCallouts {
     private List<Account > accs;
     public CalloutBatchApex(List<Account> accs) {
         this.accs = accs;
     }

    public Iterable<String> start(Database.BatchableContext BC) {
        return new List<Integer> { 1, 2, 3 };
    }
 
    public void execute(Database.BatchableContext info, List<integer> iteration) {
        // Make the callout to the web service and import the records to Salesforce for the iteration.
        String responseStrng = response.getBody();
        insertAccountMethod.methodone(responseStrng);
    }
 
    public void finish(Database.BatchableContext info) {}
}

then you can use this constructor for execute batch
List<Account> accounts = new List<Account>();
// populate list

CalloutBatchApex c = new CalloutBatchApex(accounts );
DataBase.executeBatch(c,1);