Randomly select a string from strings.xml in Android - 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.

Related

Pulling individual strings from string arrays at random

Im trying to pull individual strings from a string array at random, and display it on screen(in android studio). But i cant seem to find a solution anywhere.
Its a simple string array, and i need to pull one at a click of a button. My string array is pretty standard and set up like this:
<string-array name="string_array1">
<item>Sentence 1</item>
<item>Sentence 2</item>
</string-array>
You can user java String array or ArrayList of String in Activity like:
Java String Array Example in Activity :
1)define an Array
String string_array1[]={"Sentence 1","Sentence 2"};
Get value from the array :
Sting zeroIndexValue=string_array1[0];
Sting oneIndexValue=string_array1[1];
2) ArrayList Example:
define ArrayList of String:
ArrayList<String> string_List=new ArrayList<String>();
Add value to List:
string_List.add("Sentence 1");
string_List.add("Sentence 2");
Get value from List:
string_List.get(0);
string_List.get(1);
fetch array from string file
String[] string_array1 = getResources().getStringArray(R.array.string_array1);
Now generate random value and fetch it from array.
Random rand = new Random()
int Low = 0;
int High = string_array1.length-1;
int value = rand.nextInt(High-Low) + Low; //It will generate random number in the given range only.
String printed_value = string_array1[value];

getResourceEntryName() :can i manage to get "R.id.+getresourceentryname(R.string.myString)"?

im trying to resolve the following problem : i named my string resource like that in my xml string file :
<string name="array_nature">Nature</string>
<string name="array_architecture">Architecture</string>
<string name="array_arts">Art/Literature</string>
<string name="array_cinema">Cinema/TV/Radio</string>
<string name="array_geography">Geographie</string>
<string name="array_leisure">Loisirs</string>
<string name="array_music">Musique</string>
<string name="array_people">People</string>
<string name="array_sciences">Sciences</string>
<string name="array_technology">Technologie</string>
<string-array name="array_category">
<item>#string/array_nature</item>
<item>#string/array_architecture</item>
<item>#string/array_arts</item>
<item>#string/array_cinema</item>
<item>#string/array_geography</item>
<item>#string/array_leisure</item>
<item>#string/array_music</item>
<item>#string/array_people</item>
<item>#string/array_sciences</item>
<item>#string/array_technology</item>
</string-array>
i also have string-arrays corresponding to those two strings :
<string-array name="array_nature">
<item>Species</item>
<item>Plant</item>
<item>Animal</item>
<item>CelestialBody</item>
<item>Asteroid</item>
<item>Galaxy</item>
<item>Planet</item>
<item>Satellite</item>
<item>Star</item>
</string-array>
<string-array name="array_architecture">
<item>AmusementParkAttraction</item>
<item>Building</item>
<item>MilitaryStructure</item>
<item>Infrastructure</item>
<item>Airport</item>
<item>RouteOfTransportation</item>
<item>Bridge</item>
<item>HistoricPlace</item>
<item>Monument</item>
<item>Park</item>
<item>Zoo</item>
</string-array>
as you can see, the attribute name of my string (name = "array_nature") is exactly the same as the string-array name.
My goal is to avoid an annoying if, else if, else if ... code in my activity... So is that possible to get Something like that in my java code?
int myStringArray = R.id.+getResourceEntryName(R.string.array_nature);
and i stuck in this method
public void getchoicearray() {
Spinner sp = ((Spinner)findViewById(R.id.spinner_category));
int id = getResources().getIdentifier(getResources().getResourceEntryName(sp.getSelectedItem()./*how to get the entry
name of selected spinner item*/), "array", getPackageName());
choiceArray = id;
ArrayAdapter a = ArrayAdapter.createFromResource(this, choiceArray, android.R.layout.simple_spinner_item);
((Spinner) findViewById(R.id.spinner_choice)).setAdapter(a);
}
or any other value corresponding to a spinner choice...
EDIT : added xml spinner content
you can use public int getIdentifier (String name, String defType, String defPackage) to retrive the id at runtime.
name is the name of the resource. The one you specified in the the name attribute in the xml
defType is the type of the resource. E.g. drawable. In your case you have to use "array", because the resource you want is an array.
defPackage, is the package name of your app. You can retrieve it using getPackageName().
If you want to retrieve the id of array_nature, you will have:
int myStringArray = getResources().getIdentifier("array_nature", "array", getPackageName())
getIdentifier returns 0 it the resource can't be found. So you should always check if the return value is grater than 0
Resources res = getResources();
String[] planets = res.getStringArray(R.array.array_nature);
Do the above one in strings.xml.

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

Get Array from string.xml

I have a string in my string.xml whose structure is like this.
string.xml
<string name="my" formatted="false">As*#*Bs*#*Cs</string>
and I am fetching this string in my main file like this.
main.java
String h1 = getResource().getString(R.string.my);
and my output is like this.
h1=As*#*Bs*#*Cs
but I want output in an array without regex like this.
h1[0]="As",h1[1]="Bs",h1[2]="Cs";
What should I change to get the above output? Any help would be appreciated
Have you tried?
String[] stringArray = h1.split("\\*#\\*");
I advise you to store your string as a string array in the following manner :
<resources>
<string-array name="my">
<item>As</item>
<item>Bs</item>
<item>Cs</item>
</string-array>
</resources>
You will be able to retrieve you array in the following manner :
String [] h1 = getResources().getStringArray ( R.array.my );
After stroring your xml string in h1 String . You need to apply split on h1 string.
Try this.
String h1= "As*#*Bs*#*Cs";
String[] test = h1.split("\\*#\\*");
for(String str : test)
{
Log.i("==============", str);
}
Output :
I/==============( 1321): As
I/==============( 1321): Bs
I/==============( 1321): Cs
You can use str[0] , str[1] and str[2] to get respective string.

How to concatenate strings and integer into a variable

It is a real silly questions but I can't get it to work. I've used the search option, but couldn't not find my answer for android.
What I would like to do it the following:
In res/strings.xml i've got several strings
<string name="good0">blablabla</string>
<string name="good1">balablabla2</string>
etc
I want to show those strings randomly in a those when something happens:
Toast.makeText(this,R.string.good+(Math.random()*10), Toast.LENGTH_LONG).show();
But this doesn't work.
Thanks a lot for your help!
Use a String Array.
In strings.xml:
<resources>
<string-array name="messages">
<item>blablabla</item>
<item>blablabla</item>
</string-array>
</resources>
Then, in code you will have something like:
String[] messages = getResources().getStringArray(R.array.messages);
Random r = new Random();
String message = messages[r.nextInt(messages.length)];
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
R.string.good is an int because it refers to a Resource. This int IDENTIFIES a string in an XML file. Android provides a getString() for its resource identifiers.
Android Docs on String Resources
You'll have to get the String out of the resource file this way, then concatenate as normal.
You can't do that.
You will have to use a switch block.
String myString;
switch(Math.random() * 10) {
case 0:
myString = getString(R.string.good1);
break;
}
Toast.makeText(this, myString, Toast.LENGTH_LONG).show();
If you have multiple string values or integer values and you to store it in a single string then String Builder is the best for this
type of operation, For Example you have a string array and you want to
store in a single string and then display this string then use this
method. it will work hundred percent and it is too much suitable for
this type of problems.**
String my_str=null;
StringBuilder bldr=new StringBuilder();
for(int j=0;j<5;j++)
bldr.append(phonearray[j]).append(",");
my_str=bldr.toString();
here in this case i am assigning phone array to a single string and
then i will display it etc...

Categories

Resources