Perform action based on screen presence (Android JAVA)


Details 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()) {;
} else if(screenBisShown) {;

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



Can I see what code is in your screenAisShown() function?

I can guess that you call driver.findElement in that function, and because element is not displayed on the screen it returns NullPointerException. What you have to do is to put try catch block around and if Exception is hit, you return false.

…don’t forget to do the same for screenBisShown().


Thanks for your response. in the screenAisShown() function, am returning the boolean value.
here is the code that added in another class.

public Boolean privacyNoticeScreenIsShown() {
return privacyNoticeTitle.isDisplayed();

Am calling the above method in my test class with try catch. Please find here. I used the same try catch in screenB as well.

try {
if (privacy.privacyNoticeScreenIsShown())
catch (NoSuchElementException e)


This line of code is the problem and should be like this:

public Boolean privacyNoticeScreenIsShown(){
    driver.findElement(.....) //privacyNoticeTitle
    return true;
}catch(Exception e){
    return false;


Thanks a ton. It worked