'Only the original thread that created a view hierarchy can touch its views [2]

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)
    }

} 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source