I have a ListView showing names of countries.
I have stored the names in strings.xml as a string-array called country_names.
In populating the ListView, I use an ArrayAdapter which reads from strings.xml:
String[] countryNames = getResources().getStringArray(R.array.country_names);
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, R.layout.checked_list, countryNames);
myList.setAdapter(countryAdapter);
Now I also have a CountryCode for each country. When a particular country name is clicked on the ListView, I need to Toast the corresponding CountryCode.
I understand implementing a HashMap is the best technique for this. As far as I know, the HashMap is populated using put() function.
myMap.put("Country",28);
Now my questions are:
Is it possible to read the string.xml array and use it to populate the Map? I mean, I want to add items to the Map, but I must be able to do so by reading the items from another array. How can I do this?
The basic reason I ask is because I want to keep the country names and codes in a place where it is easier to add/remove/modify them.
The string-arrays are stored in strings.xml. Where must similar integer arrays be stored? In values folder, but under any specific XML file?
As one of the possibilities, you may store 2 different arrays in XML: string array and integer array, and then programmatically put them in the HashMap.
Definition of arrays:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_names">
<item>USA</item>
<item>Russia</item>
</string-array>
<integer-array name="countries_codes">
<item>1</item>
<item>7</item>
</integer-array>
</resources>
And code:
String[] countriesNames = getResources().getStringArray(R.array.countries_names);
int[] countriesCodes = getResources().getIntArray(R.array.countries_codes);
HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for (int i = 0; i < countriesNames.length; i++) {
myMap.put(countriesNames[i], countriesCodes[i]);
}
It may be a file with any name. See this
Related
I am creating the currency format feature with list preference.
List of entries are as follows:
<string-array>
.....
<item>Australia</item>
<item>Canada</item>
<item>United Kingdom</item>
<item>United States</item>
<item>Uruguay</item>
.....
</string-array>
And the corresponding list of values:
<string-array>
.....
<item>$</item>
<item>$</item>
<item>£</item>
<item>$</item>
<item>$U</item>
.....
</string-array>
When I select Australia, the United States becomes selected. This is because both entries have the same value and the system chooses the last item if there are duplicate values. How should we overcome this issue easily? I can use unique value with a prefix or suffix to solve the duplicity but this will lead me to do more work to encode and decode the value whenever needed.
I have tried to set the preference dynamically with no luck:
....
CharSequence[] entries = currencyPreference.getEntries();
for (int index = 0; index < entries.length; index++) {
if (entries[index].equals(entryCurrency)) {
currencyPreference.setValueIndex(index);
}
}
.....
Updated:
After searching a lot I have concluded that I had to use another list to accomplish this.
<string-array name="entry_values_currency">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
<string-array name="currency_symbols">
<item>$</item>
<item>$</item>
<item>£</item>
<item>$</item>
<item>$U</item>
</string-array>
And get the symbol as follows:
String currency = getResources().getStringArray(R.array.currency_symbols)[Integer.parseInt(currencyPreference.getValue())];
In your case, you can use HASHSET java collection library. Hashset is basically used when you need to store unique data.
- Declare a hashet of type String.
- Extract the strings from the list array and store them one by one in the hashset using the for loop with condition size and increment.
- Then declare an ArrayList of type String.
- Create the for loop with condition hashset size and increment and use arraylist 'addAll()' to store the hashset data into your new arraylist.
- The above step is because hashset doesnt store data in an indexing way and so it becomes trouble while getting the index specific data.
Hashset<String> hashset = new Hashset<>();
hashset.add("your list array data");
Arraylist<String> arraylist = new Arraylist<>();
arraylist.addAll(hashset);
These is how you will declare and initialize the hashset and arraylist.
I have a resource file called suggestions.xml which is translated to a couple of languages. These XML files contain just <string> values.
Now, I'd like to retrieve all the strings in the current locale's suggestions.xml file. How do I do that? I know I can retrieve single strings by their ID's, but I'd like to get all the strings in the XML file instead.
I wonder why would you need to do this. Still, you can use the generated R class to iterate over all kinds of resources.
Field[] fields = R.string.class.getFields();
String[] stringNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
stringNames[i] = fields[i].getName();
}
You can declare your strings like this.
<string-array name="fruitcategory_array">
<item>Apple</item>
<item>Bananas</item>
<item>Mangoes</item>
<item>Grapes</item>
<item>Other</item>
</string-array>
In your activity class, you can access them like the following.
String[] categories;
categories=getResources().getStringArray(R.array.fruitcategory_array);
Just store your Local Strings in an Array in your suggestions.xml file.
I'd like to know a better approach to improve performance of my program. The objective is to load resources automatically, I'm using names of string or string-array elements. For example, if I have the next resources:
<string name="temperature">temperature</string>
<string name="pressure">pressure</string>
<string name="velocity">velocity</string>
...
<string-array name="measures">
<item>#string/temperature</item>
<item>#string/pressure</item>
<item>#string/velocity</item>
...
</string-array>
<string name="name_temperature">Temperature</string>
<string name="name_pressure">Pressure</string>
<string name="name_velocity">Velocity</string>
...
<string-array
name="name_measures">
<item>#string/name_temperature</item>
<item>#string/name_pressure</item>
<item>#string/name_velocity</item>
...
</string-array>
<string-array name="units_temperature">
<item>K</item>
<item>°C</item>
<item>°F</item>
<item>R</item>
</string-array>
I'm loading resources this way:
measuresMap = new HashMap<String, String>();
String[] measures = getResources().getStringArray(R.array.measures);
for(int i = 0; i < measures.length; i++){
measuresMap.put(measures[i], getResources().getString(getResources().getIdentifier("name_" + measures[i], "string", getActivity().getPackageName())).toString());
}
i.e. I'm mapping the string-array values from 'measures' to it's corresponding string 'name_<>'.
I'm using a Spinner to select the measure, for example, 'Temperature':
measureSpinner = (Spinner) view.findViewById( R.id.spinnerConverter );
setSpinner(measureSpinner, R.array.name_measures, android.R.layout.simple_spinner_item, android.R.layout.simple_spinner_dropdown_item);
When an item is selected, a method retrieves the key from the Map depending on the item's string of the Spinner (getKeyByValueFromMap from here):
String[] units = getResources().getStringArray(getResources().getIdentifier("units_" + getKeyByValueFromMap(measuresMap, measureSpinner.getSelectedItem().toString()), "array", getActivity().getPackageName()));
public <T, E> T getKeyByValueFromMap(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
I need to do this to populate a NumberPicker:
String[] units = getResources().getStringArray(getResources().getIdentifier("units_" + getKeyByValueFromMap(measuresMap, measureSpinner.getSelectedItem().toString()), "array", getActivity().getPackageName()));
I think this is somehow inefficient. I read something about loading arrays with a TypedArray. I thought of a multidimensional String array. The objective is the same: load resources automatically (driven by the for loop to populate the Map). Is a HashMap the best option? It would be easier if a resource name could be defined with another resource string:
<string name="#string/temp">Temperature</string>
Every time I read a question about performance, a bell rings in my mind asking if there is really a performance issue. If you work with a small quantity of values, you won't really notice any bad performance. And if you work with lots of data, you should probably use sqlite instead.
If you won't be using #string/name_temperature per se, it can go directly on the array and make it similar to the example on the documentation
And yes, you can make use of TypedArray:
TypedArray measures = context.getResources().obtainTypedArray(R.array.name_measures);
It understands length() and getString(index).
Back to your code, I don't really understand your need of a map here, unless you are really worried of putting the strings directly in your arrays instead of the IDs.
Also, I see you use the name to generate the id of the Spinner; in this context, it doesn't help the performance and, more important, it does not make the code clearer either.
So the real answer:
I would take the references to the Spinners somewhere accessible. It might be nice to reify the need of a different key, and make a sublclass of Spinner that can convert indexed positions to the strings I want. In other words, delegate to the Spinner the responsibility of storing and converting positions to strings.
Since here I do need to map positions to the strings (instead of just the IDs), I could use a simple String[] and then, onItemSelected just access the position, geting the desired String, or setting it as selected (then when you ask your Spinner which value it has, you can just ask for its selected value, remember you now have it's reference on some attribute).
i want to get a string from strings.xml. i know how to do this. but my problem is something else:
i have a String Variable which changes every time, and every time it changes, i want to look at strings.xml and check if that String variable exists in Strings.xml, then get text.
for example:
String title="sample title" \\ which changes
String city= "sample city"
String s = getResources().getString(R.string.title);
in the third line: title is a String, and there isn't any "title" named String in Strings.xml
how can i do this? please help me
As far as I can tell, you could use public int getIdentifier (String name, String defType, String defPackage). Its use is discouraged, though.
To use it (I haven't done it but I had once read about the method) you probably would need to:
int identifier = getResources().getIdentifier ("title","string","your.package.name.here");
if (identifier!=0){
s=getResources().getString(identifier);
}
else{
s="";//or null or whatever
}
One thing you could do to get strings from dynamic keys is make 2 string arrays and put them in a HashMap.
arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="title_keys">
<item>title1</item>
<item>title2</item>
<item>title3</item>
</string-array>
<string-array name="title_values">
<item>Real Title 1</item>
<item>Real Title 2</item>
<item>Real Title 3</item>
</string-array>
</resources>
And in your code:
String[] titleKeys = getResources().getStringArray(R.array.title_keys);
String[] titleValues = getResources().getStringArray(R.array.title_values);
HashMap<String, String> titles = new HashMap<String, String>();
for(int i = 0; i < titleKeys.length; i++) {
titles.put(titleKeys[i], titleValues[i]);
}
Finally, to get your titles from a dynamic key:
titles.get(titleFromSomewhere);
You wouldn't. You use strings.xml for constant strings. What you want to do is one of two things.
1)You want a String to be constant, but one of a few options (for example, one item in a list of countries). In this case, put all of the options in strings.xml, and hold which one you're currently using in an int. When you need to get the actual string, use getString().
2)It really can be any string (for example, a user entered name). In that case it doesn't go in strings.xml at all, you just use a String variable.
This can not be done, resources are converted to unique ints in R.java, and those are used to look up your actual string resources.
So R.string.title is actually something like 0x78E84A34.
You can write your own class which manages strings for you utilizing a HashMap<String,String> to lookup full strings for shorter "key" strings.
I have multiple different categories and in each category I use one string resource to populate a ListView like so:
<string-array name="list">
<item>item1</item>
<item>item2</item>
<item>item3</item>
</string-array>
I call them like so:
String[] list = getResources().getStringArray(R.array.list);
How can I combine these into one String[] to use as an "All" list.
you can combine two Array List into a single one Like this:
ArrayList<String> first;
ArrayList<String> second;
second.addAll(first);
Since you use Simple Array there a multiple way to change arrays to arrayList, you can fetch for it on the net. But why you are not storing them on a single array in xml file that you call it global_content for exemple. You are waisting time and memory for this!!