+ Start a Discussion
Anto HotelbedsAnto Hotelbeds 

Apex batch- variable common to the three methods

Hi,

 

I the following code:

 

global class AccountSynchBatch implements Database.Batchable<sObject>,Database.AllowsCallouts{
    
    global Integer result=0;
    global Integer Mains=0;
    global Integer branches=0;
    global Integer errores=0;
    global AccountSynchBatch()
	{
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
	{
        return DataBase.getQueryLocator([SELECT Id,Account_to_be_Synch__c,Atlas_Branch_Number__c FROM account WHERE Account_to_be_synch__c=True]);
	}
	
    global void execute(Database.BatchableContext BC,List<sObject> scopeAcc)
	{	
        for (Integer i=0;i<scopeAcc.size();i++){ 
            if (scopeAcc.get(i).get('Atlas_Branch_Number__c')==-1){
            	result=myCallOuts.SyncMainAccount(scopeAcc.get(i).Id);
            	Mains=mains+1;
            }else{
                result=myCallOuts.SyncBranchAccount(scopeAcc.get(i).Id);
                branches=branches+1;
            }
            if (result==1){
                scopeAcc.get(i).put('Account_to_be_synch__c',False);
            }else{
            	errores++;
            }
    	}
        update scopeAcc;
        system.debug('Mains:'+Mains);
        system.debug('Branches:'+Branches);
        system.debug('Errores:'+errores);
	}
    
    global void finish(Database.BatchableContext BC)
	{
    	//Send an email to the User after your batch completes
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		String[] toAddresses = new String[] {'a.tejado@hotelbeds.com'};
		mail.setToAddresses(toAddresses);
		mail.setSubject('Apex Batch Synch Job is done');
		mail.setPlainTextBody('The batch Apex Synch job processed with the result: Main Accounts Synch: '+Mains+', Branches Accounts Synch: '+Branches+', Errores: '+errores);
		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}

}

 

When I try to acces to the three variables Mains, Branches and Errores in the finish method, even though Im sure I introduce a value in them in the execute method, I always get a 0 in the mail.

 

How do I have to declare the variables to be able of accessing them from any method?

 

Thanks,

 

Antonio

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You must use the interface Database.stateful. See http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm for details.

All Answers

sfdcfoxsfdcfox

You must use the interface Database.stateful. See http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm for details.

This was selected as the best answer
Anto HotelbedsAnto Hotelbeds

The solution was to add Database.Stateful:

 

global class AccountSynchBatch implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful{

 

Thanks a lot sfdc