+ Start a Discussion
LinkYogiLinkYogi 

variable is not incrementing in apex class

Hi All,

My issue is variable(counter) is not incrementing. 
I am running the class in batches, but debug statement 'counter prev' only gives 1.

Apex Code:

global class Update_Records{

    //**********************
    //Declare Variables
    //*********************
    public string testmrksig{set;get;}    
    public string x;
    public string y;
    public List<opportunity> OppList  {set;get;}
    public string oppString{get;set;}
    public string respons{get;set;}
    public List<Opportunity> opper = new list<opportunity>();
    public Map<string,Decimal> MrktRatngMap{get;set;}
    public Map<string,string> CompUrlMap{get;set;}
    public Map<string,string>dossierurlMap{get;set;}
    public Map<string,string>dossierurlsummarymap{get;set;}
    public string mapKey{get;set;}
    ID userId =UserInfo.getUserId();
    public List<SelectOption> AvilIns { get; set; }
    public String SeltIns {get;set;}
    private ApexPages.StandardController stdController;
  
    //***************
    //Constructor
    //***************
    
    public Update_Records()
    {
        MrktRatngMap = new Map<string,Decimal>();
        CompUrlMap = new Map<string,string>();
        dossierurlMap = new map<string,string>();
        dossierurlsummarymap = new map<string,string>();
        //OppData();
        Opportunity ope= new opportunity();
    }
    
    //***********************************************************************
    //Method to send request and parse response related to opportunities
    //*********************************************************************** 
    
    public void OppData(){
    Integer counter=0; 
    Integer batchsize=150;
    OppList =[select id, name, Marketing_Signal__c  from opportunity];
     for(Opportunity opp: OppList)
     {
        counter+=1;
        if(opp.name <> null){
            if(oppString == null){
            String url = EncodingUtil.urlEncode(opp.name,'UTF-8');
                oppString = '&names[]='+url;
            }
            else{
            String url = EncodingUtil.urlEncode(opp.name,'UTF-8');
                oppString = oppString + '&names[]='+url;
            }
        }
  
        system.debug('counter prev** '+counter);
        if (math.mod(counter,batchsize)==0)
        {
        system.debug('counter** '+counter);
        list<Marketingsignalwrapper>mswlist= new list <Marketingsignalwrapper>();   
    for(opportunity oop:OppList)
    {
    if(MrktRatngMap.containsKey(oop.name)!=True ){ 
    
     oop.Marketing_Signal__c = MrktRatngMap.get(oop.name);
    }
 
      Marketingsignalwrapper  Temp = new Marketingsignalwrapper (oop);
      mswlist.add(temp);
      
      }
      mswlist.sort();
      opper.clear();  
    for (Marketingsignalwrapper  o1 : mswlist ) 
    {  
       opportunity o2= new opportunity();
    {
     opper.add(o1.oppy);  
    }
    }
    HttpRequest htreq = new HttpRequest();
    String initialUrl = 'https://app.linkyogi.com/api/v1/companies/search?userId=' + UserId + oppString;
    htreq.setEndpoint(initialUrl);
    htreq.setMethod('POST');
    htreq.setHeader('APIKEY', '67546e2238254a5c557205d624814a32ad35cf96');
    Http http = new Http();
    
    try
    {
    system.debug('response statement**** ');
    HttpResponse res=new HttpResponse();
    if(!Test.IsRunningTest())
        res =   http.send(htreq);
    else
    res.setBody(//);
    respons = res.getBody();
   system.debug('*******----------'+respons);
     string dossier_url;
     string dossier_summary_url; 
     string marketing_signal;  
     string company_url;
     string present; 
     string names;
     boolean nameCheck = False;
    List<Companies> compList = new List<Companies>();
    JSONparser parser = JSON.createparser(respons);
        while (parser.nextToken() != null) {
             if (parser.getCurrentToken() == JSONToken.START_OBJECT){
                while(parser.nextToken() != null){
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME ) {
                   if(nameCheck == False){
                       names = parser.getText();
                       nameCheck = True;
                     }
                 }
                 
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'dossier_url')) {
                    parser.nextToken();
                    dossier_url = parser.getText();
                }
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'dossier_summary_url')) {
                    parser.nextToken();
                    dossier_summary_url= parser.getText();
                }
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'marketing_signal')) {
                    parser.nextToken();
                    marketing_signal = parser.getText();
                }
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'company_url')) {
                    parser.nextToken();
                    company_url = parser.getText();
                }
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'present')) {
                    parser.nextToken();
                    present= parser.getText();
                }
                if(parser.getCurrentToken() == JSONToken.END_OBJECT){
                    Companies com = new Companies(names,dossier_url ,dossier_summary_url,marketing_signal, company_url,present);
                    compList.add(com);
                    dossier_url = null;
                    dossier_summary_url=null;
                    marketing_signal = null; 
                    company_url = null;
                    present = null;
                    nameCheck = False;
                }
                
                }
            }
        }
     
       for(Companies com: compList){
            if(com.present == 'true'){
            MrktRatngMap.put(com.ComName, Decimal.ValueOf(com.marketing_signal));
            CompUrlMap.put(com.ComName, com.company_url);
            dossierurlsummarymap.put(com.ComName, com.dossier_summary_url);  //prad
            dossierurlMap.put(com.ComName, com.dossier_url );
            x= dossierurlMap.get(com.ComName);
            system.debug('----------------------------------------------> x'+x);
           }
             if(MrktRatngMap.containsKey(com.ComName)==True){
            mapKey=mapKey+' '+com.ComName;
            testmrksig+='::'+com.ComName+'::'+com.marketing_signal;
         }
     }
     }
     catch(System.CalloutException e) 
    {
        System.debug('A Callout Exception of method Oppdata: ' + e.getMessage());  
    }
    
    }
    counter=0;
   } 
   }  

    //*************************************
    //Inner class to Combine Json Response
    //*************************************

    public class Companies{
        public string dossier_url {get;set;}
        public string dossier_summary_url{get;set;}
        public string marketing_signal {get;set;}
        public string company_url{get;set;}
        public string present {get;set;}
        public string ComName{get;set;}

        public Companies( string nm,string durl,string dsurl, string MarkSg, string comUrl,string prsnt){
        
            this.dossier_url = durl;
            this.dossier_summary_url=dsurl;
            this.marketing_signal = MarkSg;
            this.company_url = comUrl;
            this.present = prsnt;
            this.ComName = nm;
        }
    }
   global class Marketingsignalwrapper implements Comparable 
   {
    public opportunity oppy{get;set;}
     global Marketingsignalwrapper(opportunity op) {
       oppy = op;
    }
   global Integer compareTo(Object compareTo)
   {
   Marketingsignalwrapper msw=(Marketingsignalwrapper)compareTo;
   Integer returnValue = 0;
   if (oppy.Marketing_Signal__c>msw.oppy.Marketing_Signal__c) {
            // Set return value to a positive value.
            returnValue = 1;
        } else if (oppy.Marketing_Signal__c< msw.oppy.Marketing_Signal__c){
            //Set return value to a negative value.
            returnValue = -1;
        }
      
        return returnValue;     
    } 
   }
}
 
Best Answer chosen by LinkYogi
Amit Chaudhary 8Amit Chaudhary 8
Hi Link Yogi,

In your OppData() Method you are setting counter as 0 again . 
public void OppData(){
    Integer counter=0; 
    Integer batchsize=150;
    OppList =[select id, name, Marketing_Signal__c  from opportunity];
     for(Opportunity opp: OppList)
     {
        counter+=1;


Please create  counter variable as Static method and try to declaire at Class level.
 
global class Update_Records{

    //**********************
    //Declare Variables
    //*********************
    public string testmrksig{set;get;}

    public Static Integer counter=0 ;


and your method should be like below
public void OppData(){
    Integer counter=0; 
    Integer batchsize=150;
    OppList =[select id, name, Marketing_Signal__c  from opportunity];
     for(Opportunity opp: OppList)
     {
        counter+=1;


Please let us know if this will help you .

Thanks
Amit Chaudhary

All Answers

LinkYogiLinkYogi
I am calling Update_Records.oppdata method from the batch class 
LinkYogiLinkYogi
Requesting to answer the problem
Amit Chaudhary 8Amit Chaudhary 8
HI Link Yogi,

Please use Stateful batch job in this case other wise every time your counter valuable in will re-initalize.
Sample code you can see in below post
https://developer.salesforce.com/forums?id=906F00000008zJ5IAI


Please let us know if this will help  you.

Thanks
Amit Chaudhary
amit.salesforce21@gmail.com
LinkYogiLinkYogi
@Amit, I have already applied Database.Stateful in the batch class. but my problem is when I call the Oppdata() method, then for the ' for loop', counter is not incrementing.  I have used system.debug for the same. Please look into the issue.
Amit Chaudhary 8Amit Chaudhary 8
Hi Link Yogi,

In your OppData() Method you are setting counter as 0 again . 
public void OppData(){
    Integer counter=0; 
    Integer batchsize=150;
    OppList =[select id, name, Marketing_Signal__c  from opportunity];
     for(Opportunity opp: OppList)
     {
        counter+=1;


Please create  counter variable as Static method and try to declaire at Class level.
 
global class Update_Records{

    //**********************
    //Declare Variables
    //*********************
    public string testmrksig{set;get;}

    public Static Integer counter=0 ;


and your method should be like below
public void OppData(){
    Integer counter=0; 
    Integer batchsize=150;
    OppList =[select id, name, Marketing_Signal__c  from opportunity];
     for(Opportunity opp: OppList)
     {
        counter+=1;


Please let us know if this will help you .

Thanks
Amit Chaudhary
This was selected as the best answer
LinkYogiLinkYogi
@Amit, Bhai. still getting the same result. counter is not incrementing after 1.

My batch class is given below:

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

  global Map<string,Decimal> MrktSignals;   
global map<string,string>Dosierurl;   
global map<string,string>DosierSummaryurl;      global final string query = 'select id, name, Marketing_Signal__c,dosierurl__c,dosiersummaryurl__c from opportunity';   global Database.QueryLocator start(Database.BatchableContext BC)    
{
  Update_Records op = new Update_Records();        
op.OppData();        
MrktSignals =  op.MrktRatngMap.clone();        
system.debug('MrktSignals** '+MrktSignals );        
Dosierurl= op.dossierurlMap.clone();        
system.debug('Dosierurl** '+Dosierurl);        
DosierSummaryurl= op.dossierurlsummarymap.clone();        
system.debug('DosierSummaryurl** '+DosierSummaryurl);     
return Database.getQueryLocator(query);
  }
  global void execute(Database.BatchableContext BC, List<sObject> batch)   
 {    
     try
     {  
      for(Sobject so :batch)   
     {     
       opportunity opp1 = (opportunity)so;                  
if(MrktSignals.containsKey(opp1.name) && MrktSignals.get(opp1.name) <> null){               so.put('Marketing_Signal__c',MrktSignals.get(opp1.name));                 
 }
           if(Dosierurl.containsKey(opp1.name) && Dosierurl.get(opp1.name) <> null)
{
                         so.put('dosierurl__c',Dosierurl.get(opp1.name));                  
}  
          if(DosierSummaryurl.containsKey(opp1.name) && DosierSummaryurl.get(opp1.name) <> null)
{
                         so.put('dosiersummaryurl__c',DosierSummaryurl.get(opp1.name));      
           }    
    }      
    if (batch.size()>0)      
    {    
          Database.SaveResult[] list_save=Database.Update(batch, false);          
for (Database.SaveResult sr: list_save)        
  {              
if (sr.isSuccess())
             {  
                system.debug( ' **** ' + sr.getId());           
   }      
        else     
         {       
           for (Database.Error err: sr.getErrors())                      
system.debug(err.getStatusCode()+' **** '+err.getMessage()+ ' **** '+err.getFields());                      
           }    
      }        
    }  
    }      
catch(System.QueryException e)
     {   
        System.debug('System.QueryException on oppwithmarketing batch class ' + e); 
       }
  }
  global void finish(Database.BatchableContext BC)
 {       
 system.debug(LoggingLevel.WARN, 'Batch Job Complete');  
 }
}
 
LinkYogiLinkYogi
@All, My issue is not resolved. If anyone could help me regarding the same. Please let me know.
Amit Chaudhary 8Amit Chaudhary 8
Please define counter vaiable in differnt class and use the same in every class

public class counterHandler {
public static Integer counter = 0 ;
}
 
LinkYogiLinkYogi
@Amit, Ur above both answers are working. Thanks for the same.