How to write XML content in Java for Android?

I need a little bit of help…I want to write scores to an XML file on click of a save button and retrieve saved scores automatically the next time the app starts up.

I have written the following code to save the score but unfortunately it’s not working. No file is created at all:

    public void savescore() throws TransformerException, ParserConfigurationException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document xmlDoc = docBuilder.newDocument();
        Element scores = xmlDoc.createElement("score");

        Element adityag= xmlDoc.createElement("name1");
        name1.appendChild(xmlDoc.createTextNode(name1.getText().toString()));
        Element ameyg= xmlDoc.createElement("name2");
        name2.appendChild(xmlDoc.createTextNode(name2.getText().toString()));
        Element akshadag= xmlDoc.createElement("name3");
        name3.appendChild(xmlDoc.createTextNode(name3.getText().toString()));
        Element anirudhg= xmlDoc.createElement("name4");
        name4.appendChild(xmlDoc.createTextNode(name4.getText().toString()));
        Element aashig= xmlDoc.createElement("name5");
        name5.appendChild(xmlDoc.createTextNode(aname5.getText().toString()));
        Element dhvanig= xmlDoc.createElement("name6");
        name6.appendChild(xmlDoc.createTextNode(name6.getText().toString()));
        Element mering= xmlDoc.createElement("name7");
        name7.appendChild(xmlDoc.createTextNode(name7.getText().toString()));
        Element swapnilg= xmlDoc.createElement("name8");
        name8.appendChild(xmlDoc.createTextNode(name8.getText().toString()));
        Element architg= xmlDoc.createElement("name9");
        name9.appendChild(xmlDoc.createTextNode(name9.getText().toString()));
        Element shreyag= xmlDoc.createElement("name10");
        name10.appendChild(xmlDoc.createTextNode(name10.getText().toString()));

        scores.appendChild(name1);
        scores.appendChild(name2);
        scores.appendChild(name3);
        scores.appendChild(name4);
        scores.appendChild(name5);
        scores.appendChild(name6);
        scores.appendChild(name7);
        scores.appendChild(name8);
        scores.appendChild(name9);
        scores.appendChild(name10);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(xmlDoc);
        StreamResult result = new StreamResult(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "RummyScore" + "/" + "userData.xml"));
        transformer.transform(source, result);
    }

What is going wrong with my code?

EDIT : Empty XML file is created.


Source: xml

Leave a Reply