Boolean isPresent returns NoSuchElementException

Appium Server Ver - 1.3.1
Java-client Ver - 2.0
platform - Android
Testing on Real Device

I was trying to find a element by this locator strategy -

boolean isPresent = getAndroidDriver().findElement(By.id(id).isDisplayed();

Its not returning false instead, we get NoSuchElementException
this is not really specific to a locator (id, name, text or whatever)

For previous version 1.2.4 it was working fine.

Let me know what all details i should provide.

Thanks
Shrey

Hi there,

the isDisplayed method is a little tricky. It first looks into UIHierarchy to get the element and then checks if it’s displayed (elements can also be covered or disabled, still being present in the hierarchy.
So in order to get an actual result IT HAS to be present. Otherwise the find Element method is throwing the Exception.

Another way of achieving the goal if element/s are present is to use a WebElement array.

try:

ArrayList list = wd.findElementsByID(androidID);
boolean isPresent = list.size > 0;

So you look for Elements having this ID, if list.size equals 0, this Element is not present (not present in UIHierarchy AND Screen)

That way you wont trigger an exception or failure, cause looking for elements in array can also return null, without failing or getting a NoSuchElementException.

But I agree that the isDisplayed() method is not really clarified, hence there are other methods like isEnabled(), isVisible()

Sers

2 Likes

isDisplayed() is for webelements, works well only for webelements invoked by webdriver.

but yours is elements invoked by androiddriver. so you can try the below code.
public boolean isAndroidElementPresent(String appiumresourceId){

    try{
        UiObject obj = new UiObject(new UiSelector().resourceId(appiumresourceId));
    }catch(Exception e){
        e.printStackTrace();
        return false;
      
    }
    
    return true;
}

Nice Solution - really helped :smile:

@balu how can it used for ios?

for optimal solution refer to all the threads on https://github.com/appium/java-client/issues/574

1 Like