[SalesForce] Batch finish method getting null values

I'm implementing an apex batch process.

public class BatchName implements Database.Batchable<XYZClass.wrapper>,Database.Stateful{

I have declared an integer variable as public and assigning value to it in execute method.

Public Integer Counter=0;

When I try to access it in finish method, I am getting null value.

While declaration, when i set it to zero, I'm getting zero.
I'm unable to get the assigned integer value.

I'm using the database.stateful, as it allows you to maintain state.

Please help me. Am I overlooking anything here?

Best Answer

From the documentation:

Using State in Batch Apex

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 is considered five transactions of 200 records each.

If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.

The following works for me...

public class Throwaway implements Database.Batchable<SObject>, Database.Stateful
{
    public Integer batches;
    public Throwaway() { batches = 0; }
    public Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator([SELECT Id FROM Account]);
    }
    public void execute(Database.BatchableContext bc, List<SObject> scope)
    {
        batches++;
    }
    public void finish(Database.BatchableContext bc)
    {
        system.assert(false, batches);
    }
}
Related Topic