Android Is it possible to define a map in an XML file? Android Is it possible to define a map in an XML file? xml xml

Android Is it possible to define a map in an XML file?


A simpler option would be to use two arrays. This has the benefit of not iterating the xml file again, uses less code and its more straight forward to use arrays of different types.

<string-array name="myvariablename_keys">   <item>key1</item>   <item>key1</item></string-array><string-array name="myvariablename_values">   <item>value1</item>   <item>value2</item></string-array>

Then your java code would look like this:

String[] keys = this.getResources().getStringArray(R.array.myvariablename_keys);String[] values = this.getResources().getStringArray(R.array.myvariablename_values);LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();for (int i = 0; i < Math.min(keys.length, values.length); ++i) {   map.put(keys[i], values[i]);}


How can I define a map in XML?

<thisIsMyMap>  <entry key="foo">bar</entry>  <entry key="goo">baz</entry>  <!-- as many more as your heart desires --></thisIsMyMap>

Put this in res/xml/, and load it using getResources().getXml(). Walk the events to build up a HashMap<String, String>.


You can always embed Json inside your strings.xml file:

res/values/strings.xml

<string name="my_map">{"F":"FOO","B":"BAR"}</string>

And inside your Activity, you can build your Map in the onStart method:

private HashMap<String, String> myMap;@Overrideprotected void onStart() {    super.onStart();    myMap = new Gson().fromJson(getString(R.string.my_map), new TypeToken<HashMap<String, String>>(){}.getType());}

This code needs Google Gson API to work. You can do it using the built-in Json API in the Android SDK.

And As for accessing the Map statically, you can create a static method:

private static HashMap<String, String> method(Context context) {    HashMap<String, String> myMap = new Gson().fromJson(context.getString(R.string.serve_times), new TypeToken<HashMap<String, String>>(){}.getType());    return myMap;}