从 android 资源文件中存储和提取地图

Store and extract map from android resource file

我想用键值对实现 android 选项卡。

目前我已经在我的代码中使用地图存储了它。

我想将这些键值对映射存储在 android 资源中并从资源中提取它。

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

执行此操作的最佳做​​法是什么。

如果键值对不是复杂对象,最好的方法是将它们存储在SharedPreferences中。 参考:

如果它们很复杂,将其存储在内部存储器中。 参考:

如果您还想将其存储在xml中,请参考:

解析 xml 的函数(来源:):

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;
}

您可以使用共享首选项来存储键值对。您可以优先选择以键值格式永久存储少量数据。