ProAslan
ProAslan

Reputation: 63

Android Studio Kotlin show next textview integer

Im trying to create a generator, when i click the start button, the textview gives me a a random number. This works great, but i want to show the numbers still i click stop so it must give me every few secons a new random number from my mutable List. How could I do this? My first opinion was, recursive function.

private fun run() {
    var x = 0
    var randomListe = mutableListOf<Int>()
    randomListe.add(Random.nextInt())
    x++
    for (element in randomListe) {
        var x = 0
        val zahlInListe = randomListe[x]
        //     Thread.sleep(1_000)
        // I tried while here
        textView.text = ("${randomListe[x]} \n das ist die Random Zahl moruk\n")

    }
}

Upvotes: 0

Views: 104

Answers (1)

Praveen
Praveen

Reputation: 3486

You can launch a coroutine block in lifecycleScope for this and you can also remove redundant x for keeping the current index to show the last value, you can use the last method of ArrayList to get the last value in the list

Make changes to your run method and return a Job object from it so you can cancel it later when the user taps on the stop button.

private fun run(): Job {
    return lifecycleScope.launch {
        while(true){
            delay(1000)

            var randomListe = mutableListOf<Int>()
            randomListe.add(Random.nextInt())
            textView.text = ("${randomListe.last()} \n das ist die Random Zahl moruk\n")
        }
    }
}

Now keep the return job value in a variable, on calling the run method

private var job: Job? = null
 
job = run() 

Call cancel on job when the user taps on the stop button

btnStop.setOnClickListener{
    job?.cancel()
}

Upvotes: 1

Related Questions