I am trying to get images out of my /res folder dynamically and I am just confused on the next part. I looked around StackOverflow and saw this example which is what I needed to start off with:
String fName = "android.resource://j.l.library11/drawable/" + itemName;
I thought though that since its in my /res folder it would be:
String fName = "android.resource://j.l.library11/drawable/res/" + itemName;
Which 1 of these 2 would be correct?
Also, I am just confused on what my next few steps would be to get to the point where I can set my ImageView (iView) with the image from my /res folder (itemName). The only thing I can think of off the top of my head is:
File file = new File(fName);
and then get the hash code
int itemHashCode = file.HashCode()
and then use that as
iView.setImageResource(itemHashCode).
Would that work or does anyone know the correct solution to this?
Images placed in res/drawable are automatically compiled by AAPT to integer mappings inside of your R.java class. You can set the image on an ImageView using:
myImageView.setImageResource(R.drawable.nameOfYourImage);
EDIT: I'm not clear on why you'd want to do what you're doing, but setting the resource of an ImageView with the hashcode of your image will cause a ResourceNotFoundException.
EDIT: If you're trying to be able to set the image dynamically based on an association with some data from a database, then take advantage of the fact that you have compiled drawables by saving the int of of your R.drawable.imagename in a new integer column in your DB. Then you can simply set the image like setImageResource(intFromDB). If you aren't setting up the DB in code and, therefore, don't have access to the compiled R.drawable, an alternative is something like this:
Resources res = getResources();
String mDrawableName = "image_name";
int resourceId = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resourceId);
icon.setImageDrawable(drawable );
Or even shorter, this may work:
int id = getResources().getIdentifier("mypackagename:drawable/imageName", null, null);
imageView.setImageResource(id);
I would go with reflection:
Field[] fields = R.drawable.class.getFields();
for(Field field:fields){
try {
imageView.setImageResource(field.getInt(null));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
At the moment I set a marker image for google maps on android like this:
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mon1))
Where mon1 is the name of the corresponding to a image called mon1.png in drawable folder.
How can I do it like this:
String imagename="blablaimage";
.icon(BitmapDescriptorFactory.fromResource(R.drawable.imagename))
It is not possible to do what you suggested.
Instead, a possible workaround might be to use the following function:
public int getDrawableId(String name){
try {
Field fld = R.drawable.class.getField(name);
return fld.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
and use like:
String imagename="blablaimage";
.icon(BitmapDescriptorFactory.fromResource(getDrawableId(imagename)));
If you click over R.drawable.mon1, you'll find an int declared with the name mon1 in R.java class. Everything resides in R class is basically an int. That said, you can't declare variable imagename as String to begin with. It must be int.
Everything generates in R.java class is auto generated by Android itself. Once you put some resources in appropriate directory, R.java generates corresponding resource int within so that it can be invoked from Java-end.
Bottom line, if you have an image called blablaimage somewhere in your drawable, you can (at best) do this,
int imagename= R.drawable.blablaimage;
.icon(BitmapDescriptorFactory.fromResource(imagename))
Another possibility using Resources.getIdentifier:
.icon(BitmapDescriptorFactory.fromResource(
context.getResources().getIdentifier(imagename, "drawable", "com.mypackage.myapp");
));
I'm sorry for my English .
I have a SQLite database of stored name of images in the drawable folder.
Example : R.drawable.image1 , R.drawable.image2 , ...
Is there a way that addresses stored in the database attributed to ImageViews?
Yes, you can get a Drawable by it's name, but it needs to be the full name of the resource, including the extension. So, for instance, if "R.drawable.image1" refers to an image named "image1.png", you will need to look it up by the string "image1.png".
Given the name of the image (e.g. "image1"), you can use the following method to get the resource id of the image (assuming that all of your images have the ".png" extension):
private final Map<String, Integer> iconMap = new HashMap<>();
public int getIconResourceId(final String imageName) {
String name = imageName.replace(".png", "");
Integer resourceId = iconMap.get(name);
if(resourceId == null) {
Resources resources = getResources();
resourceId = resources.getIdentifier(name, "drawable", getPackageName());
iconMap.put(name, resourceId); // cache the entry
}
return resourceId.intValue();
}
Note that the above code caches the resource ids - I use this in code for a RecyclerView, where the same image may need to be retrieved often, while scrolling the RecyclerView. If you don't need that, you may want to remove the HashMap.
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 :)
This question already has answers here:
Android, getting resource ID from string?
(14 answers)
Closed 2 years ago.
How do I get the resource id of an image if I know its name (in Android)?
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
You can also try this:
try {
Class res = R.drawable.class;
Field field = res.getField("drawableName");
int drawableId = field.getInt(null);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.
Link: Dynamically Retrieving Resources in Android
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.
You can use this function to get a Resource ID:
public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
try {
return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
throw new RuntimeException("Error getting Resource ID.", e)
}
}
So if you want to get a Drawable Resource ID, you can call the method like this:
getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());
(or from a fragment):
getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());
For a String Resource ID you can call it like this:
getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());
etc...
Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.
Read this
One other scenario which I encountered.
String imageName ="Hello"
and then when it is passed into
getIdentifier function as first argument, it will pass the name with string null termination and will always return zero.
Pass this
imageName.substring(0, imageName.length()-1)
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
}
}