SANJOY DASGUPTA
SANJOY DASGUPTA

Reputation: 95

set ImageResource is not working

I am working with an android project where I send an image name from an activity to another activity, the image is already in the drawable folder, I tried with this code shown below, But it's not working.

It's working when the code is

imageView.setImageResource(R.drawable.someimage);

but i want to display a picture among some pictures that will be decided from another activity, so I need something like below

imageView.setImageResource(R.drawable.getIntent().getStringExtra("icon"));

How can it be fixed ?

Upvotes: 1

Views: 169

Answers (3)

SANJOY DASGUPTA
SANJOY DASGUPTA

Reputation: 95

Here is the solution

 Context context = imageView.getContext();
    int id = context.getResources().getIdentifier(getIntent().getStringExtra("icon"), "drawable",
            context.getPackageName());
    imageView.setImageResource(id);

Upvotes: 0

muminers
muminers

Reputation: 1210

You can simply put Int to your Intent's Bundle reffering to requested image Resource:

intent.putExtra("icon", R.drawable.icon)

and then just use it:

int imageResource = intent.getIntExtra("icon")
imageView.setImageResource(imageResource);

This is much simplier

Upvotes: 0

DimDim
DimDim

Reputation: 381

You should get the resource Id first.

Context context = imageView.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
imageView.setImageResource(id);

I think in your case resourceName would be:

String resourceName = getIntent().getStringExtra("icon")

Upvotes: 1

Related Questions