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));