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("aditya");
adityag.appendChild(xmlDoc.createTextNode(adityas.getText().toString()));
Element ameyg= xmlDoc.createElement("amey");
ameyg.appendChild(xmlDoc.createTextNode(ameys.getText().toString()));
Element akshadag= xmlDoc.createElement("akshada");
akshadag.appendChild(xmlDoc.createTextNode(akshadas.getText().toString()));
Element anirudhg= xmlDoc.createElement("anirudh");
anirudhg.appendChild(xmlDoc.createTextNode(anirudhs.getText().toString()));
Element aashig= xmlDoc.createElement("aashi");
aashig.appendChild(xmlDoc.createTextNode(aashis.getText().toString()));
Element dhvanig= xmlDoc.createElement("dhvani");
dhvanig.appendChild(xmlDoc.createTextNode(dhvanis.getText().toString()));
Element mering= xmlDoc.createElement("merin");
mering.appendChild(xmlDoc.createTextNode(merins.getText().toString()));
Element swapnilg= xmlDoc.createElement("swapnil");
swapnilg.appendChild(xmlDoc.createTextNode(swapnils.getText().toString()));
Element architg= xmlDoc.createElement("archit");
architg.appendChild(xmlDoc.createTextNode(archits.getText().toString()));
Element shreyag= xmlDoc.createElement("shreya");
shreyag.appendChild(xmlDoc.createTextNode(shreyas.getText().toString()));
scores.appendChild(adityag);
scores.appendChild(ameyg);
scores.appendChild(akshadag);
scores.appendChild(anirudhg);
scores.appendChild(aashig);
scores.appendChild(dhvanig);
scores.appendChild(mering);
scores.appendChild(shreyag);
scores.appendChild(swapnilg);
scores.appendChild(architg);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "userData.xml"));
transformer.transform(source, result);
}
What is going wrong with my code?
EDIT: Empty XML file is now created after adding the permission suggested by @Gabriella
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>