Android: using XML to Persist Data

If you have a handful of data to be stored, using SharedPreferences to persist your data may not be very convenient. Android lets you store data as XML file and then read it back into your source.Using XML you can make up your own custom tags to store data in a file that is both human- and machine-readable.

The data can be organized hierarchically (grouped with parent and child nodes), but for this demo code I will show it for a single data hierarchy.You can easily extend the hierarchy.

Write Data

You start by adding a writeXML()

public void writeXML() {
try {  
String xmlFileName = "my_settings";
FileOutputStream fOut = openFileOutput(xmlFileName + ".xml", 
MODE_WORLD_WRITEABLE);
StringBuffer dataXML = new StringBuffer();  
dataXML.append("" + 
"my_personalized_data" + "\n"); 
OutputStreamWriter osw = new OutputStreamWriter(fOut);   
osw.write(dataXML.toString()); 
osw.flush();
osw.close();
} catch (IOException io) {
io.printStackTrace();
}
}

Read Previously Stored XML Data

private void readXML() throws XmlPullParserException, 
IOException {
String tagName = "";  
XmlPullParserFactory myfactory = XmlPullParserFactory.newInstance();  
myfactory.setNamespaceAware(true);
XmlPullParser xmlpp = myfactory.newPullParser(); 
try {   
InputStream inpst = openFileInput("my_settings.xml");  
InputStreamReader inptsr = new InputStreamReader(inpst);
BufferedReader reader = new BufferedReader(inptsr);
String str;
StringBuffer strbuf = new StringBuffer();
while ((str = reader.readLine()) != null) {
strbuf.append(str);
}
inpst.close(); 
xmlpp.setInput(new StringReader(strbuf.toString())); 
int eventType = xmlpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
} else if(eventType == 
XmlPullParser.END_DOCUMENT) {
} else if(eventType == XmlPullParser.START_TAG) 
{
tagName = xmlpp.getName();
} else if(eventType == XmlPullParser.END_TAG) {
} else if(eventType == XmlPullParser.TEXT) { 
if (tagName.contains("my_settings")) {
String myvalue = String.parseString(xmlpp.getText().toString());
}
}
eventType = xpp.next();
}
} catch (Exception FileNotFoundException){
System.out.println("File Not Found");
} 
}

The above code gets retrieves the value in a variable myvalue.