2

I am developing a small online shopping application in Android which needs to have lot of items images, I have a web service which gives the path of image present in android drawable-mdpi, My problem here that I tried this code to get the imageresource id, but it always gives me 0.

String uri = "@drawable/bangle1.png";
int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 

Is there any method, to get resource id, so that I can use it for drawable like :

Drawable res = getResources().getDrawable(imageResource);

I tried googling but most of them suggested the above method and this gives me always 0 value. Any one please help here.

madhan kumar
  • 1,560
  • 2
  • 26
  • 36
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41

3 Answers3

1

It will be better to get your images into /assets/ folder, and don't use drawable resources for that. Because Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

If you still want to use your method try getResources().getIdentifier("bangle1.png", "drawable", getPackageName());

michal.luszczuk
  • 2,883
  • 1
  • 15
  • 22
0

Thanks to all , even i tried it all suggested answers by others , it didnt resolve but i found finally the solution here: How do I get the resource id of an image if I know its name?.

it worked magically:

String mDrawableName = "bangle1";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

Here , myDrawableName should not have extension like : ".png". Thanks to all.

Community
  • 1
  • 1
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
0

Your problem is that you're writing the image name with its suffix. Try using this code:

int imageResource = getResources().getIdentifier(
    "your image name without suffix(bangle1)", "drawable", YourActivtyName.this);
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Mohsen fallahi
  • 915
  • 1
  • 10
  • 27
  • i have answered my question, here below before itself, pls see that. Any other way to get image Resource id will be accepted. – Raju Sharma Apr 22 '14 at 17:21