Search code examples
seleniumwebdriver

getting NullPointerException for inline code. I have defined the WebDriver globally, call browser method is working fine What i am doing wrong here


public class Test{
    static WebDriver driver;
    public static void main(String[] arg) throws IOException, InterruptedException {
        Test2();
    }

    public static void CallBrowserChrome() {
        try {
            System.setProperty("webdriver.chrome.driver", "G:\\Chrome\\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("https://google.com");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void Test2() throws IOException, InterruptedException {
        CallBrowserChrome();

        FileInputStream fis = new FileInputStream("G:\\Book1.xlsx");
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);
        int rows = sheet.getLastRowNum();
        System.out.println(rows);
        for (int i = 1; i <= rows; i++) {
            String value = sheet.getRow(i).getCell(0).getStringCellValue();
            System.out.println(value);
            **driver.findElement(By.xpath("//*[@id='js-main-container']"))
                    .sendKeys(value);**
        }
        }
}

//The Error is at this line Highlighted(driver in 2nd Class); I have tried giving the WebDriver inside the body of the method but that also does not work

  [1]: https://i.sstatic.net/0GzeA.png

Solution

  • This line: WebDriver driver = new ChromeDriver(); declares the driver local to CallBrowserChrome and ignores your other declaration.

    Change your first method to this:

       public static void CallBrowserChrome() {
            try {
                System.setProperty("webdriver.chrome.driver", "G:\\Chrome\\chromedriver.exe");
                driver = new ChromeDriver();// update this line
                driver.get("https://google.com");
                //...etc