-1

I am trying to set a Image View resource from a Image Data Type

Something like

//this line is not working
Image storeImage = new Image(R.drawable.butterfly);

ImageView mainImage = findViewById(R.id.mainImage);

//this line is not working either
mainImage.setImageResource(storeImage);

For my work

I need to store image in a variable then use it later for Image view

SHAH MD IMRAN HOSSAIN
  • 2,558
  • 2
  • 25
  • 44
  • 2
    Does this answer your question? [Change Image of ImageView programmatically in Android](https://stackoverflow.com/questions/16906528/change-image-of-imageview-programmatically-in-android) – ADM Apr 20 '20 at 05:01
  • no this doesn't, those are for direct image resources. I don't know why people calling duplicate without considering this properly – SHAH MD IMRAN HOSSAIN Apr 20 '20 at 05:17
  • It is a duplicate .. The `Image` class you are trying to use is of `android.media` is has noting to do with resource. because your Image is in drawable folder so you should not be using `Image` . – ADM Apr 20 '20 at 05:28
  • but how it solves my problem because my problem is to store image file for later use. there is no mention to that. is there? – SHAH MD IMRAN HOSSAIN Apr 20 '20 at 05:32
  • 1
    @ADM that dupe has an awwwwful accepted answer, it suggests setting the background rather than the image resource :-( https://stackoverflow.com/a/49685546/208273 from that question is the answer that the asker is looking for (it matches the accepted answer), but it's kinda buried. – Ryan M Apr 23 '20 at 09:28
  • Yeah @RyanM actually i found this question misleading .. it was all about saving `R.drawable.butterfly` in a variable not about `ImageView's` Src or background .. – ADM Apr 23 '20 at 09:32

3 Answers3

2

Set the drawable directly, to the view:

//store the id of the drawable
int image = R.drawable.butterfly

ImageView mainImage = findViewById(R.id.mainImage);

mainImage.setImageResource(image);
Hasan Bou Taam
  • 4,017
  • 2
  • 12
  • 22
1

In general, your image is stored, once you added it to your Drawable resource folder. You can access it with an ID which can be stored in a variable (datatype int):

int storeImage = R.drawable.butterfly;

Then you have to make your ImageView accessible as you already did:

ImageView mainImage = findViewById(R.id.mainImage);

Your code mainImage.setImageResource(storeImage); doesn't work because "storeImage" is an int, but the function expects a Drawable. Each time you want to convert the ID into a Drawable, you have to use getDrawable(storeImage);.

Therefore your whole code would look like this:

int storeImage = R.drawable.butterfly;
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageDrawable(getDrawable(storeImage));
Luca
  • 151
  • 1
  • 13
0

mainImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.butterfly));