Else condition not working

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

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.

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

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.

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

@ Durga_M
Could you please share the try catch code you used, I am facing the same issue. Thanks

@manuel_stanlove Put the if statement in try block and else statement in catch block

@ ZaidanJawaidThank you.

1 Like

Hi
This try-catch block thing is not helping me.

On using isDisplayed method, it only executes the IF part, and on using isEnabled & isSelected, it executes only the else part.

Can you please help me with it ?