You need to sign in to do that
Don't have an account?
EUS
Do List indexes actually work within "For" statements from a SELECT?
I am trying to build a List of records from a List of other objects. Afterwards I need to insert the new List created. However I get the error List Index out of bounds. Here follows the code:
List<Line__c> LMELI = new List<Line__c>();
List<TX__c> Trx = [SELECT Id, Amount__c
FROM TX__c
integer i = 0;
for (TX__c PMT : Trx) {
LMELI[i].MB__c = Ref__c; // I get the error LIST INDEX out of bounds (0)
LMELI[i].Tx__c = PMT.Id;
LMELI[i++].Amount__c = PMT.Amount__c;
} // for PMT ends here
INSERT LMELI;
List<Line__c> LMELI = new List<Line__c>();
List<TX__c> Trx = [SELECT Id, Amount__c
FROM TX__c
integer i = 0;
for (TX__c PMT : Trx) {
LMELI[i].MB__c = Ref__c; // I get the error LIST INDEX out of bounds (0)
LMELI[i].Tx__c = PMT.Id;
LMELI[i++].Amount__c = PMT.Amount__c;
} // for PMT ends here
INSERT LMELI;
For (..){
Line__c newLine = new Line__c();
newLine.MB__c = Ref__c;
....
LMELI.add(newLine);
}
insert LMELI;
All Answers
Make sure that the list is not empty before accessing it:
List<Line__c> LMELI =[SELECT Id,MB__c,Tx__c,Amount__c from Line__c Limit 10];
List<TX__c> Trx = [SELECT Id, Amount__c FROM TX__c Limit 10];
integer i = 0;
for (TX__c PMT : Trx)
{
if(LMELI.size()> 0)
{
LMELI[i].MB__c = Ref__c;
LMELI[i].Tx__c = PMT.Id;
LMELI[i++].Amount__c= PMT.Amount__c;
}
} // for PMT ends here
INSERT LMELI;
Thanks,
Rockzz
For (..){
Line__c newLine = new Line__c();
newLine.MB__c = Ref__c;
....
LMELI.add(newLine);
}
insert LMELI;