3

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?

5
  • Anurag, can you share more of your code than just the first line? – Sebastian Kessel Mar 7 '16 at 16:25
  • 3
    Best to add the definition of your variable to the question (as e.g. static wouldn't work). – Keith C Mar 7 '16 at 16:25
  • You need to give us more context if we are to help you. – Adrian Larson Mar 7 '16 at 16:27
  • I edited the question above, i was using static variable while declaration. Keith's suggestions help me that static doesnt work.. Thanks Keith..!! – Anurag Mar 7 '16 at 16:33
  • No Adrain. The comments solved my problem. – Anurag Mar 9 '16 at 21:15
8

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);
    }
}
0

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.