Last active
February 16, 2016 21:25
-
-
Save jldubz/b01ae68fd5781411e5e3 to your computer and use it in GitHub Desktop.
Example generic XML Parser that I used to externalize configurations for an application.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/config.xml"); | |
InputStream in = new FileInputStream(configFile); | |
String ns = null; | |
SharedPreferences.Editor editor = appPreferences.edit(); | |
//editor.clear(); | |
boolean prefsEmpty = false; | |
if (!appPreferences.contains("pref_key_optionx")) { | |
prefsEmpty = true; | |
} | |
String key = null; | |
String value = null; | |
String type = null; | |
try { | |
XmlPullParser parser = Xml.newPullParser(); | |
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); | |
parser.setInput(in, null); | |
parser.nextTag(); | |
parser.require(XmlPullParser.START_TAG, ns, "config"); | |
while (parser.next() != XmlPullParser.END_DOCUMENT) { | |
if (parser.getEventType() != XmlPullParser.START_TAG) { | |
continue; | |
} | |
String name = parser.getName(); | |
// Starts by looking for the entry tag | |
if (name.equals("option")) { | |
key = parser.getAttributeValue(null, "key"); | |
value = parser.getAttributeValue(null, "value"); | |
type = parser.getAttributeValue(null, "type"); | |
if (key != null & value != null) { | |
if (appPreferences.contains(key) || prefsEmpty) { | |
if (type.equals("boolean")) { | |
editor.putBoolean(key, Boolean.parseBoolean(value)); | |
} else if (type.equals("string")) { | |
editor.putString(key, value); | |
} | |
} | |
key = null; | |
value = null; | |
type = null; | |
} | |
} | |
} | |
} catch (XmlPullParserException e) { | |
Log.e(LOGTAG, e.getLocalizedMessage()); | |
} finally { | |
editor.commit(); | |
in.close(); | |
configFile.delete(); | |
} | |
} catch (FileNotFoundException e) { | |
Log.e(LOGTAG, e.getLocalizedMessage()); | |
} catch (IOException e) { | |
Log.e(LOGTAG, e.getLocalizedMessage()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment