Question

I get no error if the document does not exist but when I try to append a new saying element I get following NullPointer Exception. I just want to add a new element at the end of my XML document.

java.lang.NullPointerException
at file.XMLWriter.writeXML(XMLWriter.java:34)
at gui.Main$1.actionPerformed(Main.java:49)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.KeyboardManager.fireBinding(Unknown Source)
at javax.swing.KeyboardManager.fireKeyboardAction(Unknown Source)
at javax.swing.JComponent.processKeyBindingsForAllComponents(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

GUI

package gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.BoxLayout;

import file.XMLWriter;
import Entity.Saying;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Main extends JFrame {

    private static final long serialVersionUID = -3565502930536078558L;
    private JButton commitButton;
    private JTextField sayingText;
    private JTextField categoryText;
    private JTextField authorText;
    private JPanel texts;
    private JPanel buttons;
    private XMLWriter writer;


    public Main(){
        setTitle("Sayings Creator");
        setSize(500, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
        setVisible(true);
        getContentPane().setLayout(new BorderLayout());
        writer = new XMLWriter();


        texts = new JPanel();

        buttons = new JPanel(new FlowLayout());
        commitButton = new JButton("Commit");
        commitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                writer.writeXML(new Saying(sayingText.getText(), categoryText.getText(), authorText.getText()));

                sayingText.setText("Saying");
                categoryText.setText("Category");
                authorText.setText("Author");

            }
        });

        sayingText = new JTextField("Saying");
        sayingText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent arg0) {
                sayingText.setText("");
            }

        });
        sayingText.setToolTipText("Saying");

        categoryText = new JTextField("Category");
        categoryText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                categoryText.setText("");
            }
        });
        categoryText.setToolTipText("Category");


        authorText = new JTextField("Author");
        authorText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                authorText.setText("");
            }
        });
        authorText.setToolTipText("Author");

        getContentPane().add(texts, BorderLayout.CENTER);
        getContentPane().add(buttons, BorderLayout.SOUTH);
        texts.setLayout(new BoxLayout(texts, BoxLayout.Y_AXIS));


        texts.add(sayingText);

        texts.add(categoryText);

        texts.add(authorText);

        buttons.add(commitButton);


        getRootPane().setDefaultButton(commitButton);

        this.validate();
    }

}

XMLWriter

package file;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import Entity.Saying;

public class XMLWriter {

    private String FILE_PATH = "sayings.xml"; 

    public void writeXML(Saying saying)
    {
        try 
        {
            File file = new File(FILE_PATH);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            if(file.exists())
            {
                Node rootElement = doc.getFirstChild();

                Element sayingParent = doc.createElement("saying");
                rootElement.appendChild(sayingParent);

                Element firstname = doc.createElement("saying_text");
                firstname.appendChild(doc.createTextNode(saying.getSaying()));
                sayingParent.appendChild(firstname);

                Element lastname = doc.createElement("category");
                lastname.appendChild(doc.createTextNode(saying.getCategory()));
                sayingParent.appendChild(lastname);

                Element nickname = doc.createElement("author");
                nickname.appendChild(doc.createTextNode(saying.getAuthor()));
                sayingParent.appendChild(nickname);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(FILE_PATH));
                transformer.transform(source, result);
            }
            else
            {
                Element rootElement = doc.createElement("sayings");
                doc.appendChild(rootElement);

                Element sayingParent = doc.createElement("saying");
                rootElement.appendChild(sayingParent);

                Element firstname = doc.createElement("saying_text");
                firstname.appendChild(doc.createTextNode(saying.getSaying()));
                sayingParent.appendChild(firstname);

                Element lastname = doc.createElement("category");
                lastname.appendChild(doc.createTextNode(saying.getCategory()));
                sayingParent.appendChild(lastname);

                Element nickname = doc.createElement("author");
                nickname.appendChild(doc.createTextNode(saying.getAuthor()));
                sayingParent.appendChild(nickname);



                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(FILE_PATH));

                transformer.transform(source, result);
            }

        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

}
Was it helpful?

Solution

Regardless of whether or not the File already exists, you are doing docBuilder.newDocument() to initialize your Document object.

Might I suggest you take a look at DocumentBuilder.parse

OTHER TIPS

Document.parse is working when file exist on your device. When file does not exist on your device then it's not working, we need Document.newDocument.

Below solution is work for me.

 try 
    {
        final File newXmlFile = new File(
                Environment.getExternalStorageDirectory() + "/audit.xml");

        String FILE_PATH = newXmlFile.getPath();

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

        if(newXmlFile.exists() == true)
        {
            docFactory.setValidating(false);

            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            Document doc = docBuilder.parse(newXmlFile);
            doc.getDocumentElement ().normalize ();


            Node rootElement = doc.getFirstChild();
            NodeList rootList = doc.getElementsByTagName("sayings");
            Node root = rootList.item(0);

            Log.i("ffffffffffffffffffffff", String.valueOf(rootElement));

            Element sayingParent = doc.createElement("saying");
            root.appendChild(sayingParent);

            Element firstname = doc.createElement("saying_text");
            firstname.appendChild(doc.createTextNode("Testss"));
            sayingParent.appendChild(firstname);

            Element lastname = doc.createElement("category");
            lastname.appendChild(doc.createTextNode("Tesedsfsdf"));
            sayingParent.appendChild(lastname);

            Element nickname = doc.createElement("author");
            nickname.appendChild(doc.createTextNode("ddddddd"));
            sayingParent.appendChild(nickname);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(FILE_PATH));
            transformer.transform(source, result);


        }
        else
        {
             DocumentBuilder newdocBuilder = docFactory.newDocumentBuilder();
             Document newdoc = newdocBuilder.newDocument();

            Element rootElement = newdoc.createElement("sayings");
            newdoc.appendChild(rootElement);

            Element sayingParent = newdoc.createElement("saying");
            rootElement.appendChild(sayingParent);

            Element firstname = newdoc.createElement("saying_text");
            firstname.appendChild(newdoc.createTextNode("sssssssssss"));
            sayingParent.appendChild(firstname);

            Element lastname = newdoc.createElement("category");
            lastname.appendChild(newdoc.createTextNode("sasaaaaaaaaa"));
            sayingParent.appendChild(lastname);

            Element nickname = newdoc.createElement("author");
            nickname.appendChild(newdoc.createTextNode("ccccccccccccc"));
            sayingParent.appendChild(nickname);


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(newdoc);
            StreamResult result = new StreamResult(new File(FILE_PATH));

            transformer.transform(source, result);


        }
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top