Sorry if the format is not good, first post ever and I don't know what all the options are.

totalRecords list size is printing as NULL in the email message body, I cannot figure out why.

global class errorRecordsCleanUp_batch implements Database.Batchable<SObject> {

    global Integer totalRecords;

    global void execute(Database.BatchableContext BC, List<ErrorRecords__c> scope) {

        List<ErrorRecords__c> errorList = new List<ErrorRecords__c>();

        for(ErrorRecords__c element:scope) {

        try {
            totalRecords = errorList.size();
            System.debug('####totalRecords size: ' + totalRecords);
            **//this debug statement if printing out the correct totalRecords size no problem**

        …//rest of the class

    global void finish(Database.BatchableContext BC) {

    String body = 'Hello,<br/><br/>Batch process to delete errors records from ErrorRecords__c table has been completed. <br/><br/>' + 'Total deleted records: ' + totalRecords;
    **//this string in printing totalRecords as NULL in the email message body, why is that?**
    …//rest of the class

There is a "marker" interface Database.Stateful that alters the way the framework manages the batchable class and ensures that fields are preserved between execute calls and through into the finish method.

Adding that to the class signature will fix the problem in part:

... implements Database.Batchable<SObject>, Database.Stateful {

and you also need to change these lines:

Integer totalRecords = 0;
totalRecords += errorList.size();

to sum the records from the multiple calls to execute.

See the "Using State in Batch Apex" section of Using Batch Apex.

  • This solved the problem, thank you! Sorry I couldn't vote up apparently I'm too new to vote. – JJCoolJ Jul 17 '14 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.