I am uploading a csv using apex programming to upload data to my custom object. I am getting this error while uploading csv file. Some the same is uploading correctly. Can one tell how to resolve this. I tried a lot but i couldn't resolve this.
Error: List index out of bounds: 5 Error is in expression '{!ReadFile}' in page
for (Integer i=1;i < filelines.size();i++)
{
String[] inputconvalues = new String[]{};
inputconvalues = filelines[i].split(',');
Contact con = new Contact();
for(Account a: accstoupload)
{
con.AccountId =accstoupload[i-1].id;
}
if(con.AccountId!= null)
{
con.Lastname = inputconvalues[36];
con.Email = inputconvalues[37];
con.Phone = inputconvalues[38];
contoupload.add(con);
}
}
try
{
insert contoupload;
}
catch (Exception e1)
{
ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Account Name associate with this Contact already exist ');
ApexPages.addMessage(errormsg);
}
return null;
Best Answer
This error occurs when you try to reference by index something in a list that does not exist. You have two lists in the sample code above 'inputconvalues' and 'accstoupload'.
inputconvalues. To receive this kind of error when using inputconvalues[] it would likely be due to one of the rows in your CSV file not having the correct number of columns in it. You can resolve this by correcting your CSV file and/or by adding some defensive code to check the size of the inputconvalues list via the size() method before accessing elements by index via inputconvalues[].
accstoupload. This looks like your code is assuming this list has the same number of items in it as the rows in your CSV file. Are you 100% sure this is the case, if not you would receive this error when your code started to process CSV rows towards the end of the file. Try giving a file with one row to test this theory.
Debug Tips: