AnswerDroid
AnswerDroid

Reputation: 1893

How to proceed even if element not found or waiting in appium for android

I am using Appium (java) for automating my android app.
Suppose I try to find a button (by class/ id / accessibility) and I don't get that - they either server keeps on searching for that particular id or throws exception.
Using try- catch is one option , but what incase if it still searching for element even after few seconds?
Kindly suggest the right approach to proceed

Upvotes: 1

Views: 4384

Answers (4)

Rohan
Rohan

Reputation: 859

WebElement feedsCatItems = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.className("android.view.View")));

You can use this. This waits for a particular element and then it moves. Here I am waiting for the view and it waits for 10 seconds. This is pretty easy.

Upvotes: 1

econoMichael
econoMichael

Reputation: 677

Here's a simple solution:

 public static Boolean elementExists(By selector) {
    List<MobileElement> elementlist = driver.findElements(selector);
    return (!elementlist.isEmpty());
}

The important part is using driver.findElements which will return a list of elements found. Then simply check if the list is empty.

Upvotes: 2

karthick23
karthick23

Reputation: 1331

Try this. I have wrapped it as a function isElementPresent() which is a boolean and returns true if element present.

public boolean isElementPresent(String identifier) throws IOException{

    MobileElement elementId = (MobileElement)driver.findElementById(identifier);

    Application_Log.info("Element found :- " , elementId);

    int totalSize = elementId.size();
    System.out.println(totalSize);

    if (totalSize!=0){

        System.out.println("Element found  : "+ elementId );

    }else{
        Application_Log.error("Element not found :- " + elementId);
        Assert.fail("Element not found :- " + elementId);
    }

    return false;
}

Upvotes: 1

Chandrashekhar Swami
Chandrashekhar Swami

Reputation: 1790

Create a method which will check element is available or not using your try-catch logic e.g

String elementID="something";
WebDriverWait wait = new WebDriverWait(driver, waitTime);
    try{
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(elementID)));
    }catch (Exception e) {
        log("INFO - "+elementID+" Element is Not Present");
        return false;
    }
return true;

If method returns true perform your operation or else assert it.

Upvotes: 2

Related Questions