reiley
reiley

Reputation: 3761

Not able to fetch resource using getResources().getIdentifier

I need to fetch a drawable using its name so that I can set it in imageView.setImageDrawable(), which takes the int value;

The string I'm using say is, img_state_btn.

Code:

int id = mContext.getResources().getIdentifier(icon, null,
                mContext.getPackageName());
imgView.setImageDrawable(mContext.getResources().getDrawable(id));

I'm receiving correct package name, but value of id is coming out to be 0.

Where I'm doing wrong?

P.S. - Do not want to use R.java

Upvotes: 1

Views: 1906

Answers (4)

GrIsHu
GrIsHu

Reputation: 23638

Try out as below :

You can get the id of an image with it's name by below code.

 int id= getResources().getIdentifier(imageName,"drawable", getPackageName());

Upvotes: 2

SHASHIDHAR MANCHUKONDA
SHASHIDHAR MANCHUKONDA

Reputation: 3322

int id = mContext.getResources().getIdentifier("drawable/"+drawablename, "drawable",mContext.getPackageName());

(or)

int id = mContext.getResources().getIdentifier(drawablename, "drawable",mContext.getPackageName());

JavaDoc for this

int android.content.res.Resources.getIdentifier(String name, String defType, String defPackage)



public int getIdentifier (String name, String defType, String defPackage) 
Added in API level 1
Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here. 

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

Parameters
name  The name of the desired resource. 
defType  Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type. 
defPackage  Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package. 

Returns
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.) 

Upvotes: 1

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

To get drawable id from name use following code. I think problem is you are passing null instead of "drawable"

int drawableResourceId = mContext.getResources().getIdentifier("nameOfDrawable", "drawable", mContext.getPackageName());

Upvotes: 2

VINIL SATRASALA
VINIL SATRASALA

Reputation: 634

You can also directly set

imgView.setImageResource(R.drawable.img_state_btn);

Upvotes: -1

Related Questions