Mano Kugan
Mano Kugan

Reputation: 219

Element is Null when using @AndroidFindBy

I am working on a cross platform scripting and I am using the page object model. I am using @AndroidFindBy(id = "")/ @iosFindBy("") annotations to identify the elements. I m unable to run my scripts as I m getting a null pointer exception.

I debugged and found that the element is Null. (please refer to the screenshot) enter image description here

I have already initialised my driver when initialising the desiredCapabilities. but I m not sure how to look for the element in the driver.

driver = new AndroidDriver<MobileElement>(url, desiredCapabilities);

The code works fine when I m only using AndroidDriver and use ,

driver.findElement(By.id(""))

But it fails when I m trying to run with @AndroidFindBy(id=""). Where do I mention about where the element should be looked in for? Any headsup or guidance would be appreciated

Upvotes: 1

Views: 4441

Answers (1)

Bill Hileman
Bill Hileman

Reputation: 2838

I create a main page object class which contains the class instantiation, then each page object class I create implements that base page object class shown below:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.support.PageFactory;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;

public class PageObject {

    AndroidDriver<AndroidElement> driver;

    public PageObject(AndroidDriver<AndroidElement> driver) {

        this.driver = driver;
        PageFactory.initElements(new AppiumFieldDecorator(driver, 30, TimeUnit.SECONDS), this);

    }

}

Your problem might be as simple as the class parameter you are passing is hard-coded, possibly to the wrong class. It should be the page object's class itself, hence "this"

Here's a segment of a page class that extends the page object above:

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AndroidFindBy;

public class CalculatorPage extends PageObject {

    public CalculatorPage(AndroidDriver<AndroidElement> driver) {
        super(driver);
        System.out.println("Calculator page class has been initialized");
    }

    @AndroidFindBy(id = "com.android.calculator2:id/formula")
    AndroidElement formula;
    @AndroidFindBy(id = "com.android.calculator2:id/result")
    AndroidElement result;

    public String getResult() {
        String text = helper.getText(result, "Result");
        if ("".equals(text)) 
            text = helper.getText(formula, "Formula");
        return text;
    }

}

Upvotes: 3

Related Questions