Alex McPherson
Alex McPherson

Reputation: 3195

Android pass image drawable via intent in activity to 2nd activity

In my intent I want to pass an image drawable to a second activity or in this case a detail view. I pass the image drawable like this from activity1

Intent i = new Intent(NewsActivity.this, DetailActivity.class);
i.putExtra("image",R.drawable.bg1);

bg1 is a png file in the app package in the drawable dir.

In the second activity I try to set the image like the below.

int imageId = getIntent().getIntExtra("image", 0);

//Image background
ImageView imageView = (ImageView) findViewById(R.id.detailBgImg);
imageView.setImageResource(imageId);

I would expect the imageView to be the passed the drawable from activity1 i.e R.drawable.bg1

Also this line confuses me.

int imageId = getIntent().getIntExtra("image", 0);

I presume getIntExtra("image" is the key that was passed from activity1 what is this default value that I have set to 0? I don't get this? Please explain.

Either way my passed image never shows if I hard code the drawable it does like the below

ImageView imageView = (ImageView) findViewById(R.id.detailBgImg);
imageView.setImageResource(R.drawable.bg1);

I am very confused! I am new to Android also so that doesn't help.

Upvotes: 1

Views: 3005

Answers (2)

Enzokie
Enzokie

Reputation: 7415

The second arguments means default value if in case your intent with a key "image" does not exist.

int imageId = getIntent().getIntExtra("image", 0);

In your code it is much better if you utilize this paramater like this.

int imageId = getIntent().getIntExtra("image", R.drawable.placeholderimage); 

Upvotes: 1

Sina KH
Sina KH

Reputation: 565

FIRST: 0 will be used when you don't pass "image" key in your intent as the default value for the imageId

SECOND: Your code seems to be ok and doesn't have any problems.. If you can't see the image even after hardcoding as you said, I thing your drawable (bg1) is too large to be displayed (or something like that) or perhaps something is wrong with your imageView and layout.....

Upvotes: 1

Related Questions