Search code examples
appiumappium-android

Perform actions based on screen presence (Android JAVA)


Say i have two screens ‘A’ and ‘B’, i want to execute action ‘1’ if screen ‘A’ is shown and action ‘2’ if screen ‘B’ is shown. Initially am checking the screen ‘A’ and ‘B’ presence using the if else statement but didn’t work. here is my code

if(screenAisShown()) 
{
button1.click;
} else if(screenBisShown) {
button2.click;
}

In the first iteration screen A is shown so the if block executes successfully and in the second iteration screen B is shown but NoSuchElementException thrown for if block and the else if is not executed

TIA


Solution

  • you can create a method isAScreenDisplayed() and isBScreenDisplayed().

    public static boolean isAScreenDisplayed(){
       try{
           return elementOfAScreen.isDisplayed();
       }catch(Exception e){
           return false;
       }
    }
    
    public static boolean isBScreenDisplayed(){
       try{
           return elementOfBScreen.isDisplayed();
       }catch(Exception e){
           return false;
       }
    }
    

    Now you can use if else condition to check which screen is displayed.

    if(isAScreenDisplayed){
       //do something
    }
    else if(isBScreenDisplayed){
       //do something
    }