Reputation: 3
I am trying to iterate the elements , where i have to get text body for every element, but after 1st element body is printed, next for next element body I am getting "java.lang.IndexOutOfBoundsException: Index: 1, Size: 1". I know this is very simple fix, but i am unable to fix it. Please help me to fix this issue.
In my below code, when "String text = KpiText.get(i).getText();" prints for 2nd time i am getting "java.lang.IndexOutOfBoundsException: Index: 1, Size: 1" error.
public void checkKPIValuesForTeam() throws InterruptedException{
List<WebElement> userNames = DifferentUsers.findElements(By.xpath("//div[@class='radio sfa-radio-red']"));
System.out.println(userNames.size());
int maxLength = userNames.size();
for(int i=0;i<maxLength;i++){
WebElement namesOfUsers = userNames.get(i);
System.out.println(namesOfUsers);
namesOfUsers.click();
List<WebElement> KpiText = KPIValues.findElements(By.xpath("//*[@id='main-content-app']/div/div[2]/div/div/div[2]/div[2]/div[1]/div/div[1]"));
System.out.println(KpiText.size());
String text = KpiText.get(i).getText();
System.out.println(text);
}
Expected is it should print the body for all the elements for iteration.
Upvotes: 0
Views: 4678
Reputation: 482
If you are iterating over List<WebElement> KpiText
it is better idea to do it like this :
List<WebElement> KpiText = KPIValues.findElements(By.xpath("//*[@id='main-content-app']/div/div[2]/div/div/div[2]/div[2]/div[1]/div/div[1]"));
for(int i=0; i < KpiText.size() - 1; i++){
WebElement namesOfUsers = userNames.get(i);
System.out.println(namesOfUsers);
namesOfUsers.click();
System.out.println();
String text = KpiText.get(i).getText();
System.out.println(text);
}
Upvotes: 0
Reputation: 679
It seems that usernames.size() is greater than the size of KpiText. When referencing the KpiText List make sure the index is actually there. So maybe a check like
if(i < KpiText.size()){
String text = ...
}
Upvotes: 0
Reputation: 196
The problem is very simple. You are using the value "i" to access the "KpiText" array. In this case, your array has only one element, so the index 1 is out of bounds, as the exception stack trace says.
If you want to print them all you should do this:
for (WebElement element : KpiText)
System.out.println(element.getText());
Upvotes: 2