Else condition not working

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

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) {
} else {

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.

Util.log(“This is service”);
Util.log(“We got a popup and it goes off”);
Util.log(“Clicking on ok button”);
Util.reportLog(“Clicking on OK button”);
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