getResourceEntryName for an array item - android

I have a string array in strings.xml as detailed below:
<string-array name="spinerArray">
<item name="one">First</item>
<item name="two">Second</item>
<item name="three">Third</item>
<item name="four">Fourth</item>
</string-array>
And I need to retrieve one of the items name not the value (one, two, three, four). So far, I know it's possible to get the name of the array using getResourceEntryName like:
getResources().getResourceEntryName(R.array.spinerArray);
Is there a way to get an item name?
Thanks.

As this is an xml, you will need a xml parser. Then you can get the values of name using
attributes.getValue("name");
Or
name = ((Element) your_node).getAttribute("name"));
using DOM parser (org.w3c.dom)

Another solution:
Resources res = getResources();
TypedArray entriesTypedArray = res.obtainTypedArray(R.array.spinerArray);
ArrayList entriesName = new ArrayList();
TypedValue v1 = new TypedValue();
for (int i1=0; i1<entriesTypedArray.length(); i1++) {
entriesTypedArray.getValue(i1, v1);
String name1 = res.getResourceEntryName(v1.resourceId);
entriesName.add(name1);
}

Related

Array in XML: insert one array into another as a part

Preparing string resources for my Android application, I've faced such a problem. I need two string arrays with 12 and 13 items, and first 11 items are common for both arrays. It would be a good idea to create array of 11 common items, then create two needed arrays contained 11 items from the 'common' array plus 1 and 2 additional items. However, I cannot find a way to do it. It is possible to reference to some xml resource, but in my case it makes necessary to include each 11 common items separately.
Thanks in advance for any idea
In your XML, you can reference common array as item:
<resources>
<string-array name="common_array">
<item>name 1</item>
<item>name 2</item>
<item>name 3</item>
</string-array>
<string-array name="new_array">
<item>#array/common_array</item>
<item>name 4</item>
</string-array>
</resources>
Then in your java code, you add following function which will convert the resource items to list of strings:
List<String> getArrayItems(int resourceId, Resources resources) {
ArrayList<String> itemList = new ArrayList<>();
TypedArray typedArray = resources.obtainTypedArray(resourceId);
for (int i = 0; i < typedArray.length(); i++) {
int type = typedArray.getType(i);
if (type == TypedValue.TYPE_STRING) {
itemList.add(typedArray.getString(i));
} else if (type == TypedValue.TYPE_REFERENCE) {
int resIdOfArray = typedArray.getResourceId(i, 0);
List<String> itemsForGivenRes = Arrays.asList(resources.getStringArray(resIdOfArray));
itemList.addAll(itemsForGivenRes);
}
}
typedArray.recycle();
return itemList;
}
Finally, you can use that function to get list of items in new_array:
List<String> arrayItems = getArrayItems(R.array.new_array, getApplicationContext().getResources());
Log.d("MyAdapter", "onCreate: " + arrayItems.toString()); // should print MyAct: onCreate: [name 1, name 2, name 3, name 4]
Note that in my example, I have considered string arrays only. With small change, you can adapt function to different arrays as well.
I hope my answer helps.

reading and writing to and from xml file on android

This is part of my string.xml file on an application that I'm trying to create:
<array name="users">
<item>
<user_name>u1</user_name>
<password>p1</password>
<email>aaa#aaa</email>
</item>
<item>
<user_name>u2</user_name>
<password>p2</password>
<email>bbb#bbb</email>
</item>
<item>
<user_name>u3</user_name>
<password>p3</password>
<email>ccc#ccc</email>
</item>
</array>
I have a problem reading the "users" two-dimensional array into a two-dimensional array on the java file. I've already created a class name "User" for the array. I'm quite stuck here. Can anybody give me a hand? Thanks
strings.xml is not for what you are trying to do here. It is supposed to have all strings that are displayed to the user to provide multi-language support.
If you want to store your app's domain data to XML file, you can create one in the assets folder and read it.
It's ok. I've solved it. Here is my code:
String[] userArray = getResources().getStringArray(R.array.users);
User[] arr = new User[3];
for(int i=0 ; i<userArray.length ; i++)
arr[i] = new User(userArray[i]);
and this is my "User" class constructor:
public User(String str)
{
int num;
str = str.substring(1);
num = str.indexOf(' ');
user_name = str.substring(0,num);
String substr = str.substring(num+1);
num = substr.indexOf(' ');
password = substr.substring(0,num);
email = substr.substring(num+1);
}
In that way I get an array of "User".

get list of the strings present in strings.xml file in Android

I want the list of strings present in the strings.xml file.
Does anyone knows how to get it??? One thing I found is it assigns the ids in sequential order inside R.java but how to get the starting id is not clear.
For Example I have 100 Strings in my strings.xml like below and I want to read in at a time not like giving getResources().getString(int id) for individual.
<string name="app_label">Calendar</string>
<string name="what_label">What</string>
<string name="where_label">Where</string>
<string name="when_label">When</string>
<string name="timezone_label">Time zone</string>
<string name="attendees_label">Guests</string>
<string name="today">Today</string>
<string name="tomorrow">Tomorrow</string>
You can declare your strings in res\values\strings.xml file like this.
<string-array name="vehiclescategory_array">
<item>Cars</item>
<item>Bikes</item>
<item>RVs</item>
<item>Trucks</item>
<item>Other Vehicles</item>
</string-array>
In your activity class, you can access them like the following.
String[] categories;
categories=getResources().getStringArray(R.array.vehiclescategory_array);
In the above list, whatever sequence you declare, the same way it is assigned to the array in your activity. Suppose Cars will be assigned to categories[0]. Hope this helps.
Field[] fields = R.string.class.getDeclaredFields(); // or Field[] fields = R.string.class.getFields();
String str = "";
for (int i =0; i < fields.length; i++) {
int resId = getResources().getIdentifier(fields[i].getName(), "string", getPackageName());
str += fields[i].getName() + " = ";
if (resId != 0) {
str += getResources().getString(resId);
}
str += "\n";
}
You will get all codes of strings with its values in "str" variable.
If you want to access all the Strings from the strings.xml file you could use reflection on the R.string class. An example can be found in this answer, you'll just need to replace drawables with strings.
You could declare an integer array with an entry for each string. I did this for an array of colors once, so I imagine it works for strings as well.
res/values/arrays.xml
<integer-array name="app_strings">
<item>#string/app_label</item>
<item>#string/what_label</item>
<item>#string/where_label</item>
<item>#string/when_label</item>
<item>#string/timezone_label</item>
<item>#string/attendees_label</item>
<item>#string/today</item>
<item>#string/tomorrow</item>
</integer-array>
Then in your code, you would loop over the array and use each value as the argument for getString().
int[] stringIds = getResources().getIntArray(R.array.app_strings);
String[] strings = new String[stringIds.length];
for (int i = 0; i < stringIds.length; i++) {
strings[i] = getString(stringIds[i]);
}
The problem is you have to manually update your arrays.xml whenever you modify your string resources, so it's certainly not ideal.
String[] categories = getResources().getStringArray(R.array.stars_array);
List<String> stringList = new ArrayList<>(Arrays.asList(categories));
use this simple one

Randomly select a string from strings.xml in Android

I need to randomly select a string defined within strings.xml file in android.
For example my strings.xml is :
<resources>
<string name="str1">Content comes here1</string>
<string name="str2">Content comes here2</string>
<string name="str3">Content comes here3</string>
</resources>
Can I randomly select one of these strings in my Activity?
Create an array contains all of your resource names you want to select:
String[] strs = new String[] {"str1", "str2", "str3"};
Get a random index:
int randomIndex = new Random().nextInt(3);
Get your random string from resource:
int resId = getResources().getIdentifier(strs[randomIndex ], "string", your_package_name);
String randomString = getString(resId);
The best way is you declare you Strings as an Array, then get it like this:
String[] arrayOfStrings = context.getResources().getStringArray(R.array.your_string_array);
String randomString = arrayOfStrings[new Random().nextInt(arrayOfStrings.length)];
Then you can use it as you like.
You would probable rather make it an array of strings (and then that is easier to select at random one of the array). Else, you can put the ids of your strings in an array and randomly select one of the items in the array.

How to add items to a stringArray in an arrayList programmatically?

This is my array.xml file in the res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="updateInterval">
<item name="1000">Pico TTS</item>
<item name="5000">Invox TTs</item>
</string-array>
</resources>
I need to add some more items to the updateInterval array list. How can I add the items that are dynamically coming from server programmatically?
You can't add item directly to that string array.
But you can use that array and dynamically add elements to that string array.
Do in this way.
String[] array = getResources().getStringArray(R.array.updateInterval);
System.out.println("--array.length--"+array.length);
List<String> list = new ArrayList<String>();
list = Arrays.asList(array);
ArrayList<String> arrayList = new ArrayList<String>(list);
arrayList.add("TTS");
array = arrayList.toArray(new String[list.size()]);
System.out.println("--array.length--"+array.length);
It is not possible to edit an xml resource dynamically, you just can have an static arraylist in case you need some data at runtime plus xml data.

Categories

Resources