Search code examples
javaselenium-webdriverappium-android

How to fix "java.lang.IndexOutOfBoundsException: Index: 1, Size: 1" problem


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.


Solution

  • 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());