I want to store list of classes inside an xml on my res, so I can use it globally just using the index.
<resources>
<array name="array_class">
<class>Dashboard.class</class>
</array>
</resources>
in my activity
int index = x; // i get the the index from database
TypedArray arrayClass = getActivity().getResources()
.(R.array.array_class);
Class myClass = (Class) arrayClass.getString(index);
It throw me an error, cannot cast String to Class.
Yeah I know, I cannot do that. So how the correct way to store array of classes on res? or any alternative way to call Class[] value globally??
Inside your resource file store full name of all classes including package name
<resources>
<array name="array_class">
<class>com.example.Dashboard</class>
<class>com.example.YourOtherClass</class>
</array>
</resources>
Then in Java code, you can retrieve by the following method
try {
int index = x; // i get the the index from database
TypedArray arrayClass = getActivity().getResources().(R.array.array_class);
Class<?> act = Class.forName(arrayClass.getString(index));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Hope it helps
Related
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
I created an application that uses the TTS engine to send feedback to the user. With the aim to improve the performance, I used the synthesizeToFile and addSpeech methods, but strings of text to be synthesized are inside the strings.xml file, so I have to invoke these methods for each string that is spoken by the TTS engine.
Since the TTS engine uses only strings whose name begins with tts_, is it possible to easily iterate over all strings that begin with tts_ within the strings.xml file?
You can get all the strings in strings.xml via reflection, and filter out only the ones you need, like so:
for (Field field : R.string.class.getDeclaredFields())
{
if (Modifier.isStatic(field.getModifiers()) && !Modifier.isPrivate(field.getModifiers()) && field.getType().equals(int.class))
{
try
{
if (field.getName().startsWith("tts_"))
{
int id = field.getInt(null);
// do something here...
}
} catch (IllegalArgumentException e)
{
// ignore
} catch (IllegalAccessException e)
{
// ignore
}
}
}
You can give them all (while defining) the resource name as "prefix"+(1..n). And in the code use,
int resid=<constant>;
for(i=1;resid!=0;i++){
resid = this.getResources().getIdentifier("prefix"+i, "strings", this.getPackageName());
}
You could put these TTS strings into a TypedArray.
you can use this code:
String[] strings = getResources().getAssets().list("string");
for (int i = 0; i < strings.length; i++) {
Log.d("aaa ", strings[i]);
}
to iterate through other resources like fonts,... just replace string with folder name.
In all my projects, i just observed that the value of strings in R.java starts with 0x7f050000 and it counts upwards, like 0x7f050001, 0x7f050002, 0x7f050003,....
You could just ++ them :D
Hope it helps :)
I would like to store drawable resources' ID in the form of R.drawable.* inside an array using an XML values file, and then retrieve the array in my activity.
Any ideas of how to achieve this?
You use a typed array in arrays.xml file within your /res/values folder that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="random_imgs">
<item>#drawable/car_01</item>
<item>#drawable/balloon_random_02</item>
<item>#drawable/dog_03</item>
</integer-array>
</resources>
Then in your activity, access them like so:
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
// get resource ID by index, use 0 as default to set null resource
imgs.getResourceId(i, 0)
// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, 0));
// recycle the array
imgs.recycle();
In the value folder create xml file name it arrays.xml
add the data to it in this way
<integer-array name="your_array_name">
<item>#drawable/1</item>
<item>#drawable/2</item>
<item>#drawable/3</item>
<item>#drawable/4</item>
</integer-array>
Then obtain it to your code this way
private TypedArray img;
img = getResources().obtainTypedArray(R.array.your_array_name);
Then to use a Drawable of these in the img TypedArray for example as an ImageView background use the following code
ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));
where index is the Drawable index.
defaultValue is a value you give if there is no item at this index
For more information about TypedArray visit this link
http://developer.android.com/reference/android/content/res/TypedArray.html
You can use this to create an array of other resources, such as drawables. Note that the array is not required to be homogeneous, so you can create an array of mixed resource types, but you must be aware of what and where the data types are in the array.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="icons">
<item>#drawable/home</item>
<item>#drawable/settings</item>
<item>#drawable/logout</item>
</array>
<array name="colors">
<item>#FFFF0000</item>
<item>#FF00FF00</item>
<item>#FF0000FF</item>
</array>
</resources>
And obtain the resources in your activity like this
Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);
TypedArray colors = res.obtainTypedArray(R.array.colors);
int color = colors.getColor(0,0);
Enjoy!!!!!
In Kotlin, you can do as:-
<integer-array name="drawer_icons">
<item>#drawable/drawer_home</item>
</integer-array>
You will get array of Image from the resource as TypedArray
val imageArray = resources.obtainTypedArray(R.array.drawer_icons)
get resource ID by the index
imageArray.getResourceId(imageArray.getIndex(0),-1)
OR you can set imageView's resource to the id
imageView.setImageResource(imageArray.getResourceId(imageArray.getIndex(0),-1))
and in last recycle the array
imageArray.recycle()
kotlin way could be this:
fun Int.resDrawableArray(context: Context, index: Int, block: (drawableResId: Int) -> Unit) {
val array = context.resources.obtainTypedArray(this)
block(array.getResourceId(index, -1))
array.recycle()
}
R.array.random_imgs.resDrawableArray(context, 0) {
mImgView1.setImageResource(it)
}
In android you can access a resource with syntax like R..
what I want to do is to reach a set of images has naming convention.
for example I have 4 files in drawable with the names :
draw_1_.jpg
how can I get the list of drawable images to List ..
This is because, I want to make a slide show.
thx
I don't believe you can trust the resource compiler to give your images sequential integer values. In the past I've always created a static array to store these.
private static int[] imgs = { R.id.draw_1, R.id.draw_2, R.id.draw_3, R.id.draw_4 };
With this you can then have a section of code like:
int curSlide = 0;
view.setBackgroundResource(imgs[curSlide]);
Although it is an old question, I just had a similar problem recently. I liked solution of jeffd, but storing a list of images ids in code is not the best idea. So, I created an xml file with the list, which I put in res/xml directory.
<?xml version="1.0" encoding="utf-8"?>
<list>
<image id="#drawable/draw_1"/>
<image id="#drawable/draw_2"/>
<image id="#drawable/draw_3"/>
<image id="#drawable/draw_4"/>
</list>
Images are stored in drawable directory and are named draw_1.jpg, draw_2.jpg, etc.
Using this sort of xml has an advantage that availability of resources is checked at compile time, so if you have a typo, it won't compile.
Retrieving the list in code is simply parsing the xml, yet it's a bit verbose. XmlPullParser has method getAttributeResourceValue that allows getting resource id without dealing with any strings.
List<Integer> list = new ArrayList<>();
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() == XmlPullParser.START_TAG &&
parser.getName().equals("image")) {
int imageId = -1;
for (int i = 0; i < parser.getAttributeCount(); ++i) {
if (parser.getAttributeName(i).equals("id")) {
list.add(parser.getAttributeResourceValue(i, -1));
}
}
}
}
}
catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
Another simpler solution would be using arrays as resources. I haven't tried this out, but you can see an example here: http://www.geeks.gallery/how-to-list-images-from-array-xml-in-android/ This is how to structure your xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="list">
<item>#drawable/draw_1</item>
<item>#drawable/draw_2</item>
<item>#drawable/draw_3</item>
</array>
</resources>
To access the array you can use this code:
TypedArray list = getResources().obtainTypedArray(R.array.list);
for (int i = 0; i < list.length(); ++i) {
int id = list.getResourceId(i, -1);
}
well, if you know the suffix of the images, you can request the identifier for a drawable by getResources().getIdentifier(...) and then using the identifier get the drawable. So if you know how many images you have, then you can create a loop and store each of the drawables in a list. Just take into account that such a lookup is relatively expensive.
You Should identify all the Image as a Drawable .. and then you can use them as you can !
I have a resources file called string.xml in res/valus directory
the file has many string resources
how can I obtain these items in an array from code ?
I tried
Field[] x=R.string.class.getFields();
but it does not work.
thanks
It works fine for me.
You might detail your problem a little more though - what doesn't work?
Note that the R.string class contains ints, not strings. Are you expecting strings? If you want a string from that resourceId int, call Context.getString(resourceId).
This is simple example of enumaration strings.You can use it.
Field[] fields = R.string.class.getFields();
for(final Field field : fields) {
String name = field.getName(); //name of string
try{
int id = field.getInt(R.string.class); //id of string
}catch (Exception ex) {
//do smth
}
}