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:
The correct way is:
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:except that
imageResourceshould have beenparsedData[4].toString()with noR.drawable.prefix. You can usecontext.getPackageName()instead of hardcoding your package name.