dancingbush
dancingbush

Reputation: 2281

Set ImageView Drawable programmatically

I am trying to set the image of a ImageView programmatically from a array of drawables but keep getting a NUllPointerException....does this method look correct for setting Image resource..

//get a random drawable
int[] imageSelection= {R.drawable.buddycheck, R.drawable.logdive3, R.drawable.sea, R.drawable.weather, R.drawable.logo1};
Random whichImage = new Random();
int theImage = whichImage.nextInt(imageSelection.length);

displayImage.setBackgroundResource(theImage);

Upvotes: 0

Views: 2360

Answers (2)

Tanmay Ranjan
Tanmay Ranjan

Reputation: 324

Try this : imageView.setImageResource(R.drawable.image);

Upvotes: 0

M.Sameer
M.Sameer

Reputation: 3151

You are setting the image resource to a random number. You need to do it like this:

int theImage = imageSelection[whichImage.nextInt(imageSelection.length)];
displayImage.setBackgroundResource(theImage);

Upvotes: 4

Related Questions