I am fairly new to kotlin and was wondering if there was to infinitely run a loop when a switch button is in the isChecked state. My code is as follows :
binding.switch1.setOnCheckedChangeListener { _, isChecked ->
if(isChecked) {
P1 = true
try {
while(P1) {
for (i in 0..10) {
Log.d(TAG, "The iterator number is $i")
}
}
} catch (e: NullPointerException) {
Log.d(TAG, "Hii")
}
}
else{
try{
// break while loop
} catch(e: NullPointerException){
}
}
While the button is in the isChecked state, I want the loop to continuously loop the for loop. Thankyou in advance for the help!1
CodePudding user response:
This problem occurs when one process block the MAIN thread (or UI thread) the of problem is ANR, to solve this, you can run this process in another thread(ex: Coroutines).
example :
CoroutineScope(Dispatchers.IO).launch {
try {
while(true) {
//the logic here
}
} catch (e: NullPointerException) {}
}
But, be careful when you access the view components in this thread because need a little treatment for this.