Else condition not working


#1

Hi,
The else condition is not working in appium;only the if part gets executed. If the element is not found else condition should execute. Please provide the suggestion for using else.

Here is my code snippet:

if(driver.findElement(By.xpath("//android.widget.TextView[contains(@text,‘Current Booking’)]")).isDisplayed()){ driver.findElement(By.xpath("//android.widget.TextView[contains(@text,‘Current Booking’)]")).click();
}
else{
driver.closeApp();
}


#2

You description suggests one of two results
a) your if condition is always being evaluated as true
b) driver.closeApp() is not behaving the way you expect

If you add a log statement before the call to driver.closeApp(), you’ll be able to determine which it is.


#3

Thanks a lot for your reply. I have used try catch and it is working fine now.


#4

So, it’s not the call to isDisplayed() that’s failing, it’s the findElement operation. If it returns null, then isDisplayed() will raise an exception since it doesn’t have a proper object operate on. If you rewrote your code to check the results of findElement in your if statement, you wouldn’t need to use try/catch.

I wonder why you are calling isDisplayed() after findElement(). The element must be visible if it is found. Also, it can be expensive to make superfluous calls to Appium if they are not necessary. I’d be tempted to rewrite the code this way

element = driver.findElement(By.xpath("//android.widget.TextView[contains(@text,‘Current Booking’)]"))
if (element) {
element.click
} else {
driver.closeApp()
}

This assumes that findElement returns an element or nil – I’m not familiar enough with the API in Java to answer that question. The check for element is not correct, but you can make that proper java code.


#5

Is this if else blocks working.
If the condition in if block fails its not going to the else block. how can we resolve this. I don’t want to change it to list and check if its empty or not every time.

example:
if(UtilsPage.pageTitle(driver).getText().contains(“Service”))
{
Util.log(“This is service”);
}
else
{
if(UtilsPage.alertTitle(driver).getText().equals(“Order”))
{
Util.log(“We got a popup and it goes off”);
UtilsPage.clickOk(driver).click();
Util.log(“Clicking on ok button”);
Util.reportLog(“Clicking on OK button”);
}
else
{
Util.log(“Complete the section”);
}
}

Thanks in advance