java SAX解析器在工作代码更改后给出NullPointerException
我正在修改一个应用程序,该应用程序从包含测验的XML文件动态加载数据并显示问题和答案。 这个改变在于我想加载一个(现在是硬编码的)文件,而不是使用JFileChooser。
这是以前工作的相关代码(未定义变量是类属性,但我不会发布整个类声明):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i < nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
现在代码不起作用:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:file.xml");
pathname = "C:file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
另外,例外:
Exception in thread "main" java.lang.NullPointerException
它发生在question.setText(e.getAttribute("value")); 调用setupQuestion("q1"); 。
编辑:有趣的足够System.out.println(fileName); 在抛出异常之前打印并且System.out.println(idno); 在它后面打印。 实际上,在重启IDE时,抛出异常后会出现回声。
我一直坚持这一段时间。 任何帮助深表感谢。
找到罪魁祸首。 我想我没有提到一切。 我忘了分配question和replies内存。 我很惭愧。
上一篇: java SAX parser giving NullPointerException after change in working code
下一篇: org.xml.sax.SAXParseException: Content is not allowed in prolog
