ChanChow
ChanChow

Reputation: 1366

NullpointerException when trying to find a WebElement

I am trying to find a webelement using the following code:

private WebElement loc_Start;
public void clickButton() {
    loc_Start.findElement(By.xpath("//button[contains(text(), 'Start')]")).click();  
}

I don't see any mistake in the code. I also tried using @FindBy annotation, which gives me same error.

Upvotes: 0

Views: 5011

Answers (3)

Akash Patel
Akash Patel

Reputation: 1

I too was getting the same error. the mistake I was doing was trying to find element using Webelement. Instead I should use Webdriver to do so, like

Webelement myelement=driver.findelement(by.xpath());
myelement.click() // or whatever function you want to perform.

After first initialisation of driver to webelement, we can use webelemnt directly to find element without using driver like

myelement.findelement(by.xpath()).click();

Note: this direct use of webelement for finding element after 1st initailsation of webdriver works function wise. In each function you have to use it like :-

Webelement myelement=driver.findelement(by.xpath());
myelement.click();

and then for next elements we can use ->

myelement.findelement(by.xpath()).click();

Hope this helps !!!

Upvotes: -1

Jeevan Adiga
Jeevan Adiga

Reputation: 448

  1. If you are trying to implement it using PageFactory,

    public class Page{ @FindBy(xpath=" //button[contains(text(), 'Start')] ") private WebElement loc_Start; public void clickButton() { // to initialize page - else u will get null pointer exception Page page = PageFactory.init(driver, Page.class); page.loc_Start.click(); } }

  2. if not using page factory

    private WebElement loc_Start = driver.findElement(By.xpath("//button[contains(text(), 'Start')]")); public void clickButton() { loc_Start.click (); }

    You are getting NullPointerException as you have not initialized loc_Start variable.

Upvotes: 3

Ben Sampica
Ben Sampica

Reputation: 3412

Your webelement is being used for some reason to find the element. Use your web driver.

Change loc_Start

 loc_Start.findElement(By.xpath("//button[contains(text(), 'Start')]")).click(); 

to your driver name

driver.findElement(By.xpath("//button[contains(text(), 'Start')]")).click(); 

Upvotes: 0

Related Questions