7

I have created an app which should choose an image randomly from an array of images. On my Emulator Nexus 5X Android 5.1 everything works as expected. As soon as I try the same on my real device Galaxy Note 10 Lite I always get the same "random" numbers in same order. I first need to restart my phone to generate a new list of "random" numbers which is then always the same. Example: My array contains 200 elements, I open the app on my Galaxy and it chooses the following random number for the image ids: 43, 12, 176, 33, 2, 78. Then I close the app and I open the app again, now it has the exact same "random" numbers again: 43, 12, 176, 33, 2, 78. I need to restart my phone to get new random numbers, which will stay the same until I restart my phone again. On my emulator everything works fine and I get new random numbers always when I restart the app as expected.

Here is my full code of my app without array list of images:

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

 val imageList = arrayOf(Image(R.drawable.image1, false),
            Image(R.drawable.image2, false),
            Image(R.drawable.image3, false))

val imageViewMain = findViewById<ImageView>(R.id.imageViewMain)
    loadNextImage(imageViewMain, imageList)

    imageViewMain.setOnClickListener {
        val dialogClickListener =
            DialogInterface.OnClickListener { _, which ->
                when (which) {
                    DialogInterface.BUTTON_POSITIVE -> {
                        loadNextImage(imageViewMain, imageList)
                    }
                    DialogInterface.BUTTON_NEGATIVE -> { }
                }
            }
        val builder: AlertDialog.Builder = AlertDialog.Builder(this)
        builder.setMessage("Nächstes Bild?").setPositiveButton("Ja", dialogClickListener)
            .setNegativeButton("Nein", dialogClickListener).show()
    }
}

private fun getNextChoice(): Int {
    return (0..1).random()
}

private fun getNextImage(imageList: Array<Image>): Int {
    val listSize = imageList.size
    var imageId: Int
    do {
        imageId = (0 until listSize).random()
    } while (imageList[imageId].played)

    imageList[imageId].played = true
    return imageList[imageId].image
}

private fun loadNextImage(imageViewMain: ImageView, imageList: Array<Image>) {
    val imageQuestionmark = R.drawable.questionmark
    val nextChoice = getNextChoice()
    if (nextChoice == 0) {
        imageViewMain.load(imageQuestionmark)
    } else if (nextChoice == 1) {
        imageViewMain.load(getNextImage(imageList))
    }
    Toast.makeText(this, "Bild hat geladen", Toast.LENGTH_SHORT).show()
}
}

Image:

data class Image(
    val image: Int,
    var played: Boolean
)

EDIT: I tried what cactustictacs suggested in the comment and create a simple app, once with the kotlin random function and once with the java random function. here is the code I used:

Kotlin:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val buttonTest = findViewById<Button>(R.id.buttonTest)

        buttonTest.setOnClickListener {
            val getRandomNumber = (0..999).random()
            Toast.makeText(this, getRandomNumber.toString(), Toast.LENGTH_SHORT).show()
        }
    }
}

Java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonTest = (Button) findViewById(R.id.buttonTest);

        buttonTest.setOnClickListener(v -> {
            int randomNumber = new Random().nextInt(999);
            Toast.makeText(this, "" + randomNumber, Toast.LENGTH_SHORT).show();
        });
    }
}

on Kotlin I get the same behavior as with my inital problem, doesnt matter what I do with the app (I CAN EVEN UNINSTALL AND INSTALL AGAIN) I always get the same set of numbers. On Java its working as exptected, as soon as I close the app I get a new set of numbers. So the error definetly lays in kotlin.

Maybe it helps, my Android version is 12 and my phone Galaxy Note 10 Lite.

7
  • If you make a basic app with a button that calls (0..999).random() or Random.nextInt(999) and displays it, do you get the same behaviour? It should be using the device's default source of randomness, so first thing I'd check is if your device is actually doing that. Maybe check if the Java classes (e.g. docs.oracle.com/javase/8/docs/api/java/util/Random.html) behave any differently Commented Aug 24, 2022 at 18:57
  • I am gonna try that out and will reply here what happens
    – rm -rf
    Commented Aug 24, 2022 at 21:06
  • @cactustictacs I updated my post with two test apps
    – rm -rf
    Commented Aug 24, 2022 at 21:30
  • 3
    I saw this issue is in the Kotin 1.7.20-Beta patch notes KT-52618 ThreadLocalRandom is not a good source of randomness on Android before SDK 34, so don't use it for Kotlin Random - is it related?
    – aSemy
    Commented Aug 24, 2022 at 22:28
  • Does Random.nextInt(999) work in Kotlin? Or is it the same? How about Random.Default? You can use a Random source in those random calls on collections, ranges etc, and there's a ``toKotlinRandom()' extension you can use on a java.util.Random() (you can call that from Kotlin), but you shouldn't need to provide one. If you're seeing this behaviour consistently with the default random generator, it might be worth reporting it as a bug on the Kotlin site. They'll know more about what you should do in this situation Commented Aug 24, 2022 at 22:30

3 Answers 3

4

I once had this issue too. My solution is to use a seeded random object instead of calling the function Random.nextSomething(). Then I seed currentTimeInMillis as the seed.

var randomGenerator = Random(System.currentTimeMillis())
var result = randomGenerator.nextInt(30, 50)
1
  • This is true because in that way you are not using kotlin Random object but Java one. Unfortunately this is not possible in KMM project.
    – pauminku
    Commented Dec 27, 2022 at 9:58
3

This is quite a terrible implementation of Kotlin defaul Random class. Java Random class tries a lot to always use a different seed on every new instance whereas Kotlin hardcoded the same seed through the whole device. How can this be a default behavior for a Random implementation. It took me quite a lot to understand it.

See Java implementation:

 public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

private static long seedUniquifier() {
    // L'Ecuyer, "Tables of Linear Congruential Generators of
    // Different Sizes and Good Lattice Structure", 1999
    for (;;) {
        long current = seedUniquifier.get();
        long next = current * 181783497276652981L;
        if (seedUniquifier.compareAndSet(current, next))
            return next;
    }
}

private static final AtomicLong seedUniquifier
    = new AtomicLong(8682522807148012L);

Aaaaaand here comes Kotlin one:

companion object Default : Random(), Serializable {
    private val defaultRandom: Random = defaultPlatformRandom()

    private object Serialized : Serializable {
        private const val serialVersionUID = 0L

        private fun readResolve(): Any = Random
    }

    private fun writeReplace(): Any = Serialized

    override fun nextBits(bitCount: Int): Int = defaultRandom.nextBits(bitCount)
    override fun nextInt(): Int = defaultRandom.nextInt()
    override fun nextInt(until: Int): Int = defaultRandom.nextInt(until)
    override fun nextInt(from: Int, until: Int): Int = defaultRandom.nextInt(from, until)

defaultRandom is a singleton always initiates with same seed...

(I took this code through the Android Studio sources...)

Note: So it was a bug on kotlin version 1.7.10 and Android api less than 33-34 something. Fixed on 1.7.20...

4
  • defaultPlatformRandom() was calling through to Java's ThreadLocalRandom. The bug was on the Android side, not in Kotlin. youtrack.jetbrains.com/issue/KT-52618/…
    – Tenfour04
    Commented Dec 12, 2022 at 14:19
  • I'm having the same problem and as far as I know I'm using kotlin 1.7.20. I have this in my gradle: implementation("org.jetbrains.kotlin:kotlin-stdlib:1.7.20"). Is this not enough? In case it helps, I have compileSdk = 33.
    – pauminku
    Commented Dec 26, 2022 at 9:19
  • 1.7.20 should be enough. Commented Dec 26, 2022 at 9:35
  • I checked with KotlinVersion.CURRENT and it's 1.7.20, but still failing. I created a new project from scratch to see if my test code is correct and it is: it's repeating the same sequence on each re-start with 1.7.10 and working fine for 1.7.20. Maybe I have some dependencies that are making it work wrong regardless of Kotlin version... I don't know what else to try.
    – pauminku
    Commented Dec 26, 2022 at 21:57
1

It looks like you're calling loadNextImage() from activity's onCreate(). That means that unless the activity is destroyed, it'll never re-generate the random IDs that you want. What happens if you force-stop the activity, and then relaunch it? I would expect that you get a new set of IDs.

If I'm right, and you want a new set of IDs every time you open the activity, then the solution is to call loadNextImage() from onResume() (and if you don't want it generated every time the activity is resumed, you'll need to include some logic that decides when to regenerate those IDs)

6
  • That function generates a new sequence every time it's called though, so it should be a random image for every click - it's not caching a set of results or anything. And the OP says it works fine on an emulator, could be an OEM issue (although for something like random number generation, that seems like a huge problem) Commented Aug 24, 2022 at 19:00
  • And I'm saying that if the activity isn't being destroyed, then nothing is being generated at all for every subsequent time that he opens the app. It already has al the IDs generated. There is no reason to cache anything -- the activity was never destroyed, so it's just showing you what was generated during 1st run. On an emulator, it could be killing the activity as soon as he presses the "back" button. But on a real device, that could just be putting it in the background until the OS has to kill it of the resources require it
    – user496854
    Commented Aug 24, 2022 at 19:03
  • I don't get what you mean - where's it storing generated IDs? There's a fixed list of Image objects, but it randomly loops through those by calling getNextImage until it finds one that still has played set to false. Calling random() should (without a Random source seeded with the same value) produce a unique sequence. The OP's seeing the same sequence every time they start over, i.e. by restarting the app Commented Aug 24, 2022 at 19:46
  • I already tried force-closing the app, also deleted the apps cache via phone settings, for whatever reason and also reinstalled the app, but unless I restart the phone, I always get the same "random" ids, at least on my real device. As I said, on emulator everything works as expected. As soon as I close the app, I get a new set of ids
    – rm -rf
    Commented Aug 24, 2022 at 21:05
  • @user496854 see edit please
    – rm -rf
    Commented Aug 24, 2022 at 21:30

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.