在main方法中获取NullPointerException

时间:2014-10-08 07:28:11

标签: java

我试图从XML中读取值。然后,在浏览器中,我想登录Gmail应用程序。在那里我得到了NullPointerException

Eclipse中使用的代码如下:

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class A {

    private static WebDriver driver;
    Properties p= new Properties();
    String url=p.getProperty("url");

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {

        A a = new A();
        String url = a.readXML("logindetails","url");
        String username = a.readXML("logindetails","username");
        String password = a.readXML("logindetails","password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        //use username for webdriver specific actions
        driver.findElement(By.id("1001")).sendKeys(url);
    }

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{
        String ele = null;
        File fXmlFile = new File("D://NewFile.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName(searchelement);


        Node nNode = nList.item(0);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
             ele=eElement.getElementsByTagName(tag).item(0).getTextContent();

        }
        return ele;
    }

}

输出结果为:

www.gmail.com
test 
test123
Exception in thread "main" java.lang.NullPointerException
at A.main(A.java:33)

2 个答案:

答案 0 :(得分:2)

private static WebDriver driver;
....
driver.findElement(By.id("1001")).sendKeys(url);

您访问driver但从未初始化它。

这就是为您提供NullPointerException

答案 1 :(得分:1)

初始化driver。例如:

如果您使用的是firefox浏览器,请尝试

WebDriver driver = new FirefoxDriver();