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", 
StringBuffer dataXML = new StringBuffer();  
dataXML.append("" + 
"my_personalized_data" + "\n"); 
OutputStreamWriter osw = new OutputStreamWriter(fOut);   
} catch (IOException io) {

Read Previously Stored XML Data

private void readXML() throws XmlPullParserException, 
IOException {
String tagName = "";  
XmlPullParserFactory myfactory = XmlPullParserFactory.newInstance();  
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) {
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 =;
} catch (Exception FileNotFoundException){
System.out.println("File Not Found");

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

By Bhaskar

My name is Bhaskar. I am a CTO and a startup techno guy with 10+ years of experience startups.
Full-time coding in Python, React, Java. Part-time coding in C++.
Interested in Music, Travelling

What excites me: anything that has the potential to disrupt the status quo.

Looking for technical support on a startup idea ?
write at : bhaskar {-at-}