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

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.

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];

Is common values shared across String-Array possible in Android XML?

For my Android development, I have 2 arrays which is very identical except for the first and last value as below.
<string-array name="minvalues">
<item>Any Value</item>
<item>100</item>
<item>200</item>
<item>300</item>
</string-array>
<string-array name="maxvalues">
<item>100</item>
<item>200</item>
<item>300</item>
<item>Any Value</item>
</string-array>
I'm thinking is there a way to define the common values i.e. 100, 200, 300 as another array and have the minvalues and maxvalues include it from it, so we could share the common values across minvalues and maxvalues. Is this possible in Android arrays xml?
I don't think there is, since the values are string, you will need to manually convert them to integers in order to look for common values using
String[] minValues = getResources().getStringArray(R.array.minvalues);
String[] maxValues = getResources().getStringArray(R.array.maxvalues);
and then convert them into int with
int[] minValsInt = Arrays.asList(minValues).stream().mapToInt(Integer::parseInt).toArray();
int[] maxValuesInt = Arrays.asList(maxValues).stream().mapToInt(Integer::parseInt).toArray();
now you can loop through each one and get the common values.
Edit
Here's the way to get the duplicates from this post
void findDupes(int[] a, int[] b) {
HashSet<Integer> map = new HashSet<Integer>();
for (int i : a)
map.add(i);
for (int i : b) {
if (map.contains(i))
// found duplicate!
}
}
Cheers

Android - R.array.[variable] in a For loop?

I'm looking for option to access array of strings defined in strings.xml in loop.
Means, I have in my strings.xml - several arrays like:
<string-array name="ques1">
<item>bla bla</item>
<item>bla bla</item>
</string-array>
<string-array name="ques2">
<item>bla bla</item>
<item>bla bla</item>
</string-array>
How can i access in my code - the arrays of ques1, ques2...etc ? (for example - i have many questions in my application with its answers, so i want to access it in generic way).
String[] stringArray = context.getResources().getStringArray(R.array.ques1);
for(String s : stringArray) {
//do something with s
}
Edit ... I just realized you want to iterate not over the array, but over several arrays. That's also possible, with :
for(int i = 0; i<max_arrays; i++) {
int id = context.getResources().getIdentifier("ques"+i, "array",
context.getPackageName());
String[] stringArray = context.getResources().getStringArray(id);
for(String s : stringArray) {
//do something with s
}
}

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

Android random non repeating string

I'm making a bingo type game. I have a 5x5 grid of imagebuttons, each with their own textview. When the app starts or is reset, I want each textview to display a random string without any one string being displayed twice during a game. I currently have the strings in a resource array, with 127 items:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="tile_text">
<item>String 1</item>
<item>String 2</item>
<item>String 3</item>
...all the way to String 127
</string-array>
</resources>
And to display a random string on each textview:
public String[] myString;
Resources res = getResources();
myString = res.getStringArray(R.array.tile_text);
Random random = new Random(System.currentTimeMillis());
int[] textViews = {
//I have all my textviews added to this array
};
for(int v : textViews) {
TextView tv = (TextView)findViewById(v);
tv.setText(myString[random.nextInt(myString.length)]);
}
The above works well, but even with 200 strings in the array to choose from, some items still show up twice. Is there a way I can get the array to shuffle and not pick the same string twice for per game? I have searched and I find info on random strings, but nothing about non repeating random strings, so apologies if this is a duplicate question.
I'd keep a list of the strings you'e already added and then keep picking new random strings until you find one that's not already in your list.
Something like this:
Vector<String> alreadyUsed = new Vector<String>();
for(int v : textViews) {
TextView tv = (TextView)findViewById(v);
String nextString;
do {
nextString = myString[random.nextInt(myString.length)];
} while (alreadyUsed.contains(nextString));
alreadyUsed.add(nextString);
tv.setText(nextString);
}

Categories

Resources