1

I want to implement android tab with key value pair .

Currently I have stored it using map in my code .

I want to store these map of key value pair in android resource and extract it from resource .

On tab change server call has to be made using stored key .

What is the best practice for doing this.

Rahul
  • 367
  • 2
  • 6
  • 27

2 Answers2

1

If the key value pairs are not complex objects, best way is to store them in SharedPreferences. Refer : https://stackoverflow.com/a/7944653/1594776

If they are complex, store it in the internal memory. Refer : https://stackoverflow.com/a/7944773/1594776

If you still want to store it in xml, refer : https://stackoverflow.com/a/10196618/1594776

Function to parse the xml (Credits : https://stackoverflow.com/a/29856441/1594776) :

public static Map<String, String> getHashMapResource(Context context, int hashMapResId) {
Map<String, String> map = new HashMap<>();
XmlResourceParser parser = context.getResources().getXml(hashMapResId);

String key = null, value = null;

try {
    int eventType = parser.getEventType();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("entry")) {
                key = parser.getAttributeValue(null, "key");

                if (null == key) {
                    parser.close();
                    return null;
                }
            }
        }
        else if (eventType == XmlPullParser.END_TAG) {
            if (parser.getName().equals("entry")) {
                map.put(key, value);
                key = null;
                value = null;
            }
        } else if (eventType == XmlPullParser.TEXT) {
            if (null != key) {
                value = parser.getText();
            }
        }
        eventType = parser.next();
    }
} catch (Exception e) {
    e.printStackTrace();
    return null;
}
return map;
}
Community
  • 1
  • 1
Yash
  • 5,225
  • 4
  • 32
  • 65
0

You can use Sharedpreferences to store key value pair. With preference, you can store smaller amount of data permanently in key value format.

Isham
  • 424
  • 4
  • 14
  • It is a part of static data i don't want to store it in shared preference or DB. Is there any other option . My requirement is to store it in any resource file . – Rahul Feb 18 '16 at 06:12
  • Do you mean resource files like string.xml? No. These files are non editable. You can use singleton class instead. – Isham Feb 18 '16 at 06:21
  • Go for creating temp file in SDCARD and read/write from there. – Isham Feb 18 '16 at 06:25