Anonim Anonim
Anonim Anonim

Reputation: 13

Kotlin Timer() probably wrong implementation

I am learning Kotlin and at the same time I try to write a simple app. Actually, I have a problem with Timer() because when I enable switch1 the second time application crashes and writing:

Timer is already cancelled.

I need to stop the timer when switch1 goes off and when switch1 goes is enabled again, timer should start counting from the beginning. Probably, I must implement this in another way, but I don't know how to do it.

Please help and sorry for my English.

import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

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

         val timer = Timer()

         switch1.setOnCheckedChangeListener { switch1, isChecked ->
             if (isChecked) {
                 root_layout.setBackgroundColor(Color.GREEN)

                 timer.schedule(object : TimerTask() {
                     override fun run() {
                         println("dfvffv")
                     } }, 2000, 2000)
             } else {
                 root_layout.setBackgroundColor(Color.LTGRAY)

                 timer.cancel()
             }
         }
     }
 }

Upvotes: 1

Views: 1654

Answers (1)

Sergio
Sergio

Reputation: 30655

Try to initialize timer every time user clicks the switch:

var timer: Timer? = null

switch1.setOnCheckedChangeListener { switch1, isChecked ->
   
    if (isChecked) {
        timer = Timer()
        root_layout.setBackgroundColor(Color.GREEN)

        timer.schedule(object : TimerTask() {
            override fun run() {
                println("dfvffv")
            } }, 2000, 2000)
    } else {
        root_layout.setBackgroundColor(Color.LTGRAY)

        timer?.cancel()

    }
}

By the description of cancel() method:

Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

So you need to create a new instance of Timer to schedule new task.

Upvotes: 2

Related Questions