Search code examples
androidseleniumautomationappium

How to switch between AndroidElement and WebElement?


I m working on Mobile Web Application Automation. Here I m using Java, Selenium and Appium. There are two fields which I m not able to automate. They are Date and drop down fields. I can able automate text fields, check boxes and radio buttons. When clicking on Date Field, there comes the Android default date picker, in which I cant able to pick a date. Here is my code below:

class openBrowser() {   
public static WebDriver driver;   
public static AppiumDriver<MobileElement> androidDriver;   
@Test   
public static void launchBrowser(){   
desiredCapabalities(...);   
androidDriver = new AndroidDriver<MobileElement>(new 
URL("http://localhost:4723/wd/hub", desiredCapabilities));    
driver = androidDriver;   
}

class pickDate() {    
MobileElement element;
try{    
element = (MobileElement) 
androidDriver.findElementByXPath("//android.view.View[@content-desc='28 May  
2017']").click();   
}catch(Exception e) { 
throw e; 
}  
}

"findElementByXPath()" looks only for the web element, but not searching for Android/Mobile element. Please refer date picker screenshot: Date picker

Kindly suggest me any solution to switch between Web Element and Android/Mobile Element. Thanks in advance.


Solution

  • I found a solution from the below link:
    switch contexts i.e Native App and Web View

    public static void switchToContext(String context) throws Exception {
        try {
            RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
            Map<String,String> params = new HashMap<>();
            params.put("name", context);
            executeMethod.execute(DriverCommand.SWITCH_TO_CONTEXT, params);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static String getCurrentContextHandle() throws Exception{
        try{
            RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
            String context =  (String) executeMethod.execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE, null);
            return context;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static List<String> getContextHandles() throws Exception{          
        try {
            RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) androidDriver);
            List<String> contexts =  (List<String>) executeMethod.execute(DriverCommand.GET_CONTEXT_HANDLES, null);
            return contexts;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }