function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kdmrkdmr 

List index out of bounds: 1

Hi, I am trying to sum up the values of a number field in an object for a particular function, when attempting to do that I encounter an error message in the for loop. The section of code is as below

Object1__c[] obj1 = [select Id, Name, Qty__c from Object1__c where lookup1id__c = :param1 and lookup2id = :param2]; for(Integer i = 0; i <= obj1.size(); i++) {

totalqty = totalqty + obj1[i].Qty__c;

}

here param1 and param2 are values that are passed from the UI to the controller. This error appears inside the forloop for the condition. I am not sure why and how to handle this.

Thanks

KD

SteveBowerSteveBower

1. Did you mean lookup2id__c in your query?

 

2. Did you initialize totalqty?

 

If those aren't the problems, post more data.

 

-S

kdmrkdmr

Yes I did mean lookup2id__c in the query and have also initialised totalqty. I have a visualforce page and this is the extension class. I am try to do a check on the save function to identify if the Qty is within the limitis.

 

  1. Object1__c is like a junction object between lookup1__c and lookup2__c.
  2. from the visualforce page I am getting the Id for the value selected for lookup1 and lookup2 and passing them to the query to identify howmany times lookup2 is repeated for lookup1 and what is the total of the Qty__c filed for all those references.
  3. I have added debug logs to find the values for param1 and param2, the array size, the total qty. I the result on save I get the error and the debug logs show values for param1 and param2, lists out the array size but shows null for totalqty.
thanks
KD

 

SuperfellSuperfell

This loop will always go 1 too many

 

for(Integer i = 0; i <= obj1.size(); i++) 

 

you need

 

for(Integer i = 0; i < obj1.size(); i++)  

SteveBowerSteveBower
Look!  In the Sky. Is it a Bird?  A Plane?  No, it's Captain Obvious!!!  :-)  -Steve
kdmrkdmr

Thanks Simon, Thanks Steve........ for the same case of summing up a field value will this sequence of steps work, or do you see anything wrong.
obj1list = [select Id, Name, Qty__c from Object1__c where lookup1id__c =: param1 and lookup2id =: param2]; 
for(Object1__c o1 : obj1list) {
totalqty = totalqty + o1.Qty__c;
}
Which of the 2 methods would be correct and appropriate.

Thanks

KD