Home > Net >  KOTLIN | Only the original thread that created a view hierarchy can touch its views
KOTLIN | Only the original thread that created a view hierarchy can touch its views

Time:03-01

When I try to start the app, after one second the app crash and this appear in the LOGCAT:

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

What I was expecting: When app opens, it shows the hour, minutes and seconds of the device and update it forever per second

Code:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Timer().schedule(object : TimerTask() {
            override fun run() {
                val textView: TextView = findViewById(R.id.dateAndTime)
                val simpleDateFormat = SimpleDateFormat("HH:mm:ss z")
                val currentDateAndTime: String = simpleDateFormat.format(Date())
                textView.text = currentDateAndTime
            }
        }, 1000)
    }

} 

CodePudding user response:

The timer thread runs on a different thread than the views

Change your code to this

val textView: TextView = findViewById(R.id.dateAndTime)

Timer().schedule(object : TimerTask() {
            override fun run() {
              
                val simpleDateFormat = SimpleDateFormat("HH:mm:ss z")
                val currentDateAndTime: String = simpleDateFormat.format(Date())

//This does the trick
runOnUiThread{
                textView.text = currentDateAndTime
}
            }
        }, 1000)
  • Related