Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I was trying to define a static hash table that makes use of resources, but I got stonewalled by the impossibility of accessing resources statically.

Then I realized that the best of all places to define a static map is in the resources files themselves.

How can I define a map in XML? I believe that if possible it should be similar to the Listpreference mechanism, with entries and entries-values.

like image 412
ilomambo Avatar asked Apr 17 '12 17:04

ilomambo


People also ask

What is map in XML?

An XML mapping transforms object data members to the XML nodes of an XML document whose structure is defined by an XML schema document (XSD). For information on mapping concepts and features common to more than one type of EclipseLink mappings, see Introduction to Mappings.

Does Android still use XML?

Android applications use XML to create layout files. Unlike HTML, XML is case-sensitive, requires each tag be closed, and preserves whitespace.

Why do we use xml file in Android?

XML tags define the data and used to store and organize data. It's easily scalable and simple to develop. In Android, the XML is used to implement UI-related data, and it's a lightweight markup language that doesn't make layout heavy. XML only contains tags, while implementing they need to be just invoked.


1 Answers

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]); } 
like image 82
vangorra Avatar answered Oct 11 '22 08:10

vangorra