Eric Gumba
Eric Gumba

Reputation: 425

Why does trying to change a TextView or show a toast within a timerTask freeze my app?

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_track_income.*
import java.util.*
import kotlin.concurrent.timerTask

class TrackIncome : AppCompatActivity() {

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_track_income)

        val time: TextView = findViewById(R.id.time)
        val money: TextView = findViewById(R.id.money)
        val timer: Timer = Timer()  
        val calculateTime = timerTask {
            val milliseconds = System.currentTimeMillis()
            var seconds: Int = (milliseconds / 1000).toInt()
            val minutes = 1
            seconds %= 60
            print("seconds are " + seconds.toString()) 
            time.text = String.format("%d.%d", minutes,seconds)

        }
        Timer("timer", false).schedule(calculateTime,1000, 1000)

    }
    fun showToast(){
    Toast.makeText(this, "Its toast!", Toast.LENGTH_SHORT).show()
    }
}

I noticed that if I write time.text within the timerTask object, or try to call showToast(), my app will crash.

Furthermore when I try to comment out "time.text = String.format("%d.%d", minutes,seconds)" and run the app just using the print statement and examine logcat, the print statement doesn't show up either. I've already read other examples of people using the Timer object, so why doesn't my method work?

Upvotes: 1

Views: 89

Answers (1)

Rohit Chauhan
Rohit Chauhan

Reputation: 1169

Toast is a UI element so it needs to run on the UI Thread, not in a background Thread

use runOnUiThread

runOnUiThread(new Runnable() {
        public void run()
        {
            Toast.makeText(yourContext, "Your Message", Toast.LENGTH_SHORT).show();
        }
    });
}

Upvotes: 1

Related Questions