How to get the Resource.Id from Value? - android

I have a image called(my_image.png) in my Drawable-mdpi folder.
my android application interacts with a webservice. It might send back "my_image". My android application should load up this image.
I am using Monodroid and I tried this
int abc = Resources.GetIdentifier("my_image","drawable",null);
Yet the result is always "0". When it should be(from the resource file)
// aapt resource value: 0x7f020000
public const int my_image = 2130837504;
Looking around and the android way seems to be similar
int i = this.getResources().getIdentifier("txt_asecondtext", "strings", this.getPackageName());
I tried passing in the package name instead of null but that did nothing.

The problem is twofold:
You need to provide a package name in the Resources.GetIdentifier() call, and not use null.
You need to use the correct package name.
The simple way to ensure you get the correct package name is to use the Android.Content.Context.PackageName property:
int id = Resources.GetIdentifier ("my_image", "drawable", PackageName);
If you don't want to/can't use Context.PackageName, then look at the build output, in e.g. the obj\Debug\android\AndroidManifest.xml file, and use the value of the /manifest/#package attribute value. For example, AndroidManifest.xml may contain:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="MonoAndroidApplication2.MonoAndroidApplication2">
<!-- ... -->
</manifest>
Thus, you could instead use:
int id = Resources.GetIdentifier ("my_image", "drawable",
"MonoAndroidApplication2.MonoAndroidApplication2");
For monodroid#lists.ximian.com subscribers, see the How to use Resources.GetIdentifier() thread, and the followup message.

You just need to format your request properly:
Instead of:
int i = this.getResources().getIdentifier("txt_asecondtext", "strings", this.getPackageName());
Try:
int i = getResources().getIdentifier("[fully qualified package]:drawable/[resource name]", null, null);
So for Resource "my_image" in package "com.example" it would look like:
int i = getResources().getIdentifier("com.example:drawable/my_image", null, null);
UPDATE: I also tested that the following works form me (including the log lines that prove it:
int i = getResources().getIdentifier(
getPackageName() + ":drawable/" + resource_name, null, null);
Log.d("EXAMPLE", "Just making sure that these IDs match: '" + i + "' == '" + R.drawable.resource_name + "'.");
This can also be formatted like you did above, which I believe I have pointed out your error:
int i = getResources().getIdentified(resource_name, "drawable", getPackageName());

For a string ressource I do like this:
String s = "nameToFetch";
String text = getString(getResources().getIdentifier("str_" + s, "string", getPackageName()));
So I think for your drawable you should call:
String s = "nameToFetch";
Drawable drawable = getDrawable(getResources().getIdentifier("d_" + s, "drawable", getPackageName()));

Related

How to set customize imageView ID?

I have several image-views in my xml file, i need to initialize and use them dynamically.
In the image currentParam.x and y are coordinates.
Is there any way to do this task.
To get a resource id out of the resource name, use this code below. i tested in my project. working like a charm.
String packageName = getPackageName();
String tempCurrent = "square" + String.valueOf(currentParams.x+1) + String.valueOf(currentPrams.y+1);
int resId = getResources().getIdentifier("square", "id", packageName);
currentImageView = (ImageView) findViewById(resId);

Android set ImageView path dynamically as string

I have 10 images on /resources/drawable folder as following names;
pr1.gif, pr2.gif, ... pr10.gif
And I can easily set an image like this;
imgview1.setImageResource(R.drawable.pr5);
But I can't set it like following;
int pr = getpr(dm);
imgview1.setImageResource(R.drawable.pr + pr);
Is there a way to set it like this or should I use switch case?
You can get the id of a drawable by name using getIdentifier():
String prefix = "pr";
int suffix = getpr(dm); // I assume this returns the image number
Resources res = getResources();
int resId = res.getIdentifier(prefix + suffix, "drawable", "my.package.name");
imgview1.setImageResource(resId);
Note you can use this for any type of resource, whether it's drawable, string, array, etc. Just make sure you change the second parameter from "drawable" to the appropriate type.

Using a Random Number in a Drawable Path

I am using a random number to set my imageButton to a random image. I am wondering if there is a way to use the random int in the file path for the drawable. This code gives a run time error for invalid integer but will compile.
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int imagePath1 = Integer.parseInt("R.drawable.image" + chooseFirstPicture);
btn1.setBackgroundResource(imagePath1);
You are parsing a String to a Integer, so your code is going to throw a NumberFormatException every time you run it.
The correct way to get a resource id from a String key is using the function getIdentifier():
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int resourceId = getResources().getIdentifier("image" + chooseFirstPicture, "drawable", getPackageName());
if (resourceId != 0) {
//Provided resource id exists in "drawable" folder
btn1.setBackgroundResource(imagePath1);
} else {
//Provided resource id is not in "drawable" folder.
//You can set a default image or keep the previous one.
}
You can find more information in the Android Resources class documentation.
Hm.. You trying to convert "R.drawable.image1" string to an integer that is impossible. During compilation nothing checks what's in the string, but when you run the app, it fails immediately.
Better to use the getResources().getIdentifier() with proper parameters (link)
I hope it helps :)

Android getResources/getIdentifier not returning ID

I have code like tthis:
String s = "replace__menu__" + data.imageid + ".png";
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable-hdpi", getPackageName());
The String s = instruction sets a value that is the same as one of names in my res/drawable-hdpi folder. However, the returned value sets RID to the value 0
Any idea why my code is not working? Am I doing something wrong?
Try this
String s = "replace__menu__" + data.imageid; // image name is needed without extention
int RID = this.getApplicationContext().getResources().getIdentifier(s, "drawable", getPackageName());
".png" is not part of a ressource name
"drawable-hdpi" I would try just 'drawable' instead

PNG file won't display in ImageView if source is set programatically

I have a png file in my res/drawable-ldpi folder. I'm working in Eclipse with the emulator, but I've tried this on my 2.2.1 Android phone and I get the same behavior. I have an ImageView and I want to set the src programatically, based on a database call. If I just put
src="#drawable.norusdpyr"
in the Activity's XML file, the file displays fine. BUT, if I put
String imageresource = "R.drawable." + parsedData[4].toString();
chart.setImageURI(Uri.parse(imageresource));
where parsedData[4].toString() = "nor_usdpyr" I don't see anything. I've also tried
String imageresource = "android.resource://" + getPackageName() + "/R.drawable." + parsedData[4].toString();
chart.setImageURI(Uri.parse(imageresource));
and
InputStream is = getClass().getResourceAsStream("/drawable/" + parsedData[4].toString());
chart.setImageDrawable(Drawable.createFromStream(is, ""));
and
String imageresource = "R.drawable." + parsedData[4].toString();
File file = new File(imageresource);
chart.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
and
Context context = getApplicationContext();
int ResID = context.getResources().getIdentifier(imageresource, "drawable", "com.KnitCard.project");
chart.setImageResource(ResID);
finally,
chart.setImageURI(Uri.parse("android.resource://" + getPackageName() + "/R.drawable.nor_usdpyr"));
doesn't work.
None of these work. What am I doing wrong? Thanks!
First, this shouldn't be working:
src="#drawable.norusdpyr"
The correct way is:
android:src="#drawable/norusdpyr"
Second, those string ids that you use in XML are only valid in XML. When the resources are built, all those strings are replaced by their respective integer values. Ideally, you won't need to load a package resource from a string name. But if you do, you can look for the field with such name, get the integral value it holds, and call setImageResource. You were quite close with this version:
int ResID = context.getResources().getIdentifier(imageresource, "drawable", "com.KnitCard.project");
chart.setImageResource(ResID);
except that imageResource should have been parsedData[4].toString() with no R.drawable. prefix. You can use context.getPackageName() instead of hardcoding your package name.
you can also use the setImageDrawable() method to work directly with the resource:
myImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.myPngFileName));
this will avoid the process of getting the ResID and then using it for access

Categories

Resources