0

Im trying to display random image whenever the app goes on. First I made a list with image ids and tried to make a random integer so that I can get random image each time by using the integer as an index of the list. Below is the code I tried.

val background_image = findViewById<ImageView>(R.id.background_image)

val drawableList = mutableListOf<Int>(R.drawable.picture_0001,R.drawable.picture_0002,R.drawable.picture_0003)
val index = Random.nextInt(drawableList.size)
val test = (1..5).random()

Toast.makeText(this,test.toString(),Toast.LENGTH_SHORT).show()

background_image.setImageResource(drawableList[index])

test and the Toast part is just for checking if other random method works. but both two ways doesn't work and shows the same random integer every time. Why isn't it working? (minSDK 21).

2
  • What do you mean by "doesn't work"? What happens when you run your code? What do you want it to do instead? Commented Aug 12, 2022 at 5:20
  • 1
    Im trying to make it to display different image randomly in each run but It just shows one image in every run time. (1..5).random() part also toasts the same integer each time Commented Aug 12, 2022 at 5:51

2 Answers 2

2

You need to use a different seed to get different results.

from Random

Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime.

You can use System.currentTimeMillis() as a seed.

val random = Random(System.currentTimeMillis())
val list = listOf(1,2,3)
val randomInt = list[random.nextInt(list.size)]
1
  • Thank you sooo much! By the way, what does "Two generators" mean? Is it "two" because I used "Random" twice in one project by "Random.nextInt(drawableList.size)" and "(1..5).random()"?? Commented Aug 13, 2022 at 6:10
0

Instead of generating a random number on your own, you can simply use the extension function of Collection class.

val list = mutableListOf(1,2,3,4,5,6,7)
val aRandomNumberFromList = list.random()
1
  • It still shows same images.. I think somthing got wrong with my project. In different project it works and the method which I tried also works. Commented Aug 12, 2022 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.