Lightweight key-value pairs for Android bundled resources

The key-value pair data representation has always been quite important in computer science. For instance, in mobile application key-value pairs are generally used to store simple data such as application preferences (with the help of a SharedPreferences[1] instance).

Key-value pairs are so nice and simple to use, developers usually bundle some "by-default" or "initial" data directly inside the Android application resources. This is obviously possible thanks to the resources loading system which associates a name to a string|color|integer|dimen|etc. value. But this system doesn't sandbox data from a Java code point of view: you can getResources().getString(R.string.prefs_1) to get a single preference but you can't get a set of all the preferences at once.

What about getting a Bundle[2] of all the key-value pairs? Wouldn't it be cleaner? The Android framework already includes some pretty-handful methods to help you do that. One of these methods is Resources#parseBundleExtras.

In order to help you load key-value pairs from your application resources, I've created a tiny utility class that let's you create a Bundle with a simple call to ResourcesAdditions.getResourcesExtras(getResources(), R.raw.extras) on the following extras.xml file (available in res/raw/):

<?xml version="1.0" encoding="utf-8"?>
<extras xmlns:android="http://schemas.android.com/apk/res/android">

    <extra
        android:name="mega"
        android:value="1000000" />

    <extra
        android:name="kilo"
        android:value="1000" />

</extras>

The main advantage of this resource key-value pairs loading mechanism is it is extremely lightweight because it relies on the Android framework. One of the disadvantages is loading doesn't look as efficient as a Gson deserialization for large data (although bundled XMLs are turned into a binary form at compile time).

All of the code is available on the following Gist: https://gist.github.com/cyrilmottier/8179328

[1]: http://developer.android.com/reference/android/content/SharedPreferences.html
[2]: http://developer.android.com/reference/android/os/Bundle.html
[3]: http://developer.android.com/reference/android/content/res/Resources.html#parseBundleExtras(android.content.res.XmlResourceParser, android.os.Bundle)
Shared publiclyView activity