getting the size of values.xml in android studio? - android

I'm doing a task in my android class, and in my values folder, I created a file called "values.xml" and in it I placed some random strings:
<string name="name1">John</string>
<string name="name2">Jane</string>
<string name="name3">Andre</string>
in my java file, I would like to get a random string, but I want this to be based on the size of the values.xml
Random random = new Random();
String randomString = getResources().getString(random.nextInt(3));
textView.setText(randomString);
this creates and fetches a random string, but instead of
random.nextInt(3);
I want it to fetch values.xml.size(); or something similar.
Is there a smart way to do this? I've searched everywhere!

You can use reflection to get all the strings in the XML value file:
Field[] fields = R.string.class.getFields();
//fields.length would be the count of all the string in your xml file
int rand = random.nextInt(fields.length)
String randomText = getResources().getString(fields[rand].getName()));

You can use for set of elements :
<string-array name="name_array">
<item>John</item>
<item>Jane</item>
<item>Andre</item>
</string-array>
And you can get size of array at runtime using below code:
int size = getResources().getStringArray(R.array.data_array).length;

Related

android R.string. retrieving value [duplicate]

This question already has answers here:
Accessing contents of R.string using a variable to represent the resource name
(4 answers)
Android, getting resource ID from string?
(14 answers)
How to get a resource id with a known resource name?
(10 answers)
Closed 3 years ago.
I'm practicing my Java and I'm trying to make something like simple text game. Now there are two main characters and each one have their own pop up text.
I've put the text in string.xml with their own names like "dialog1" "dialog2" "dialog3" and I want to retrieve the strings with R.string.dialog* but I want to make some function to change numbers something like "dialog" + int
How to make something like this??
I made it like if you tap on screeny the its displayed "dialog1" massage when you tap second time the other character should display next part "dialog2". Now I don't want to do it manually r.string.dialog1 then r.string.dialog2 I want to make function of this but I don't know how to pass value "dialog" + int.
You can put a parameter in the xml as explained in this post Are parameters in strings.xml possible?
You need to add %1$d wherever you want in the string resource so when you want to get the string you send the parameter.
<string name="dialog1"> This is %1$d</string>
And when you want to get it
getString(R.string.dialog1, "1")
If you want more parameters you change the parameter number
<string name="parameters"> Many parameters %1$d %2$d %3$d</string>
and then
getString(R.string.parameters, "1", "2", "3")
If you need to format your strings, then you can do so by putting your format arguments in the string resource, as demonstrated by the following example resource.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. Then, format the string by calling getString(int, Object...). For example:
String text = getString(R.string.welcome_messages, username, mailCount);
Quoted from: Android Documentation
If you want a method to load the values stored in strings.xml, you have to create an array of ints containing the ids of the resources.
Example:
Create messages into strings.xml:
<resources>
...
...
<string name="dialog1">My first message</string>
<string name="dialog2">My second message</string>
<string name="dialog3">My third message</string>
</resources>
Then use this method to load the values according the index of the element defined into the array:
int[] messageValues = new int[] {R.string.dialog1,R.string.dialog2,R.string.dialog3};
private String getDialogMessage(Context context, int dialogIndex){
if(dialogIndex >= messageValues.length) //Check if element exist in array
return "";
return context.getResources().getString(messageValues[dialogIndex]);
}
and these are examples of how to used the method:
System.out.println(getDialogMessage(getApplicationContext() , 0)); //get first element message.
System.out.println(getDialogMessage(getApplicationContext() , 1)); //get second element message.
System.out.println(getDialogMessage(getApplicationContext() , 2)); //get third element message.
System.out.println(getDialogMessage(getApplicationContext() , 14)); //returns "" , because the element doesnt exist into the array..

How do you use an integer from the resource file within a string in the same resource file?

Is it possible to use an integer:
<integer name="minstringlength">7</integer>
within the same resource file but within a string:
<string name="nametooshort">Please enter a name longer than #integer/minstringlength characters</string>
I presume you want to use different minimum limits based on device configuration. You can't use the #integer/minstringlength in the string content, so I think the best you can do is have a format argument and build the string yourself like this:
<integer name="minstringlength">7</integer>
<string name="nametooshort">Please enter a name longer than %1$d characters</string>
int nameMinLength = getResources.getInt(R.integer.minstringlength, 0);
String nametooshort = getString(R.string.nametooshort, nameMinLength);
This assumes you are using an Activity/Fragment, otherwise you need a Context in order to use getResources() and getString().
It can not be done in resource file.
As xml contains static content and also from android string-resource doc there is no sub tag or nested tag of <string>
It task can done easily in java file
getResources().getString(R.string.minstringlength);
getResources().getInteger(R.integer.nametooshort);
OR
Follow this post
<string name="meatShootingMessage">You shot %1$d pounds of meat!</string>
int numPoundsMeat = 123;
String strMeatFormat = getResources().getString(R.string.meatShootingMessage);
String strMeatMsg = String.format(strMeatFormat, numPoundsMeat);

Get all string resources from XML resource file?

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.

get string from Strings.xml by a variable

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.

Add resource-strings to Char Sequence

I have the following problem:
I created a Char Sequence and was able to name 4 units. I would however rather use strings from my XML file for localization purposes. Is there any way to achieve that?
final CharSequence[] choices =
//want to add strings here i.e. R.strings.lemonade
{"Coke", "Pepsi" , "Sprite" , "Seven Up" };
builderType.setSingleChoiceItems( choices, selected, new OnClickListener()
{.......
Error message:
Type mismatch: cannot convert from int to CharSequence
There's another overload of AlertDialog.Builder.setSingleChoiceItems() that takes in an int resource id for a string array of items. Put the following in an xml in res/values e.g. strings.xml:
<string-array name="choices">
<item>Coke</item>
<item>Pepsi</item>
<item>Sprite</item>
<item>Seven Up</item>
</string-array>
Then you can use it as:
builderType.setSingleChoiceItems(R.array.choices, selected, new OnClickListener(), ...
For generic cases, you can also load string array resources with Resources.getStringArray() as suggested by #Egor.
Create a string-array in strings.xml
<string-array name="choices">
<item>Coke</item>
<item>Pepsi</item>
<item>Sprite</item>
<item>Seven Up</item>
</string-array>
Then fetch it from resources
String[] choices = context.getResources().getStringArray(R.array.choices);
Then use it in setSingleChoiceItems() as is, since String implements CharSequence.

Categories

Resources