How to iterate over a listview of unknown length?

I have a list view with a hierarchy I theoretically have no knowledge of. I am attempting to accept a String array and create MobileElements for each string in it, but due to the way I’ve automated (PageFactory) defining my elements via annotations, they cannot use variables. I also don’t know that it’s valid or proper to define my annotations inside a method.

The code I’ve written, which obviously does not compile follows:

public void selectLocation(String[] location) {

    List<MobileElement> locationsList = new ArrayList<>();
    for(int i = 0; i < location.length; i++) {

        @iOSFindBy(accessibility = location[i])
        @AndroidFindBy(xpath = "//android.widget.TextView[@text='" + location[i] + "']")
        locationsList.add(i);
    }
    for (int i = 0; i < location.length; i++) {
        locationsList.get(i).click();
    }
}

I’m assuming the proper way to do this is wholly different from the way I’ve implemented.

My list hierarchy is similar to the following; my end point could vary depending on the branch I go down:

Continent 1

  • City 1
    . Room 1
    . Room 2
  • City 2
    . Building 1
    … Room 1
    … Room 2
    . Building 2
    … Room 1
    … Room 2

Use @AndroidFindBys,
Ex : @AndroidFindBys({@AndroidFindBy(xpath = “//android.widget.TextView”)})
private List locationsList;
Now iterate through the list.
Ex: for(int i = 0; i < locationsList.size(); i++) {
if(locationsList.get(i).getText().equals(location[i])) {
// TODO
}
}

Hope it hepls…

1 Like

Thanks, that was very helpful. My final code looks like the following:

@AndroidFindBys({@AndroidFindBy(xpath = "//android.widget.TextView")})
@iOSFindBys({@iOSFindBy(xpath = "//XCUIElementTypeStaticText")})
private List<MobileElement> locationsList;

...

public void selectLocation(String[] location)
{
    for(int i = 0; i < locationsList.size(); i++)
        for(int p = 0; p < location.length; p++) {
            if (locationsList.get(i).getText().equals(location[p])) {
                locationsList.get(i).click();
            }
        }
}

The only problem is if I have the same string in different levels of my hierarchy. I shouldn’t in my use-case, but anyone looking to reuse this code will want to think about that.