java SAX解析器在工作代码更改后给出NullPointerException
问题描述:
我正在修改一个应用程序,该应用程序从包含测验的XML文件动态加载数据并显示问题和答复。这个改变在于我想加载一个(现在是硬编码的)文件,而不是使用JFileChooser。java SAX解析器在工作代码更改后给出NullPointerException
下面是相关的代码之前的工作(不确定的变量是类属性,但我不会发表全班声明):
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");
。
编辑:有趣的是实际上,在重启IDE时,抛出异常后会出现回声。System.out.println(fileName);
获取异常被抛出并且被System.out.println(idno);
后印刷之前印刷。
我一直坚持这个相当一段时间。任何帮助深表感谢。
答
发现罪魁祸首。我想我没有提到一切。我忘了为question
和replies
分配内存。我很惭愧。
*“我很惭愧”* - 没有...我们都犯错误。 – 2011-05-04 00:23:27