Accessing resources from another class

I am brand new to Kotlin as well as Android. I’ve searched everywhere but could not find the solution to this. I am trying to modify a text field in the ‘class MainActivity : AppCompatActivity()’ from a running thread ‘class datarun: Runnable, MainActivity()’. But the program always crashes without any suggestions. I think this has to do with the fact that I am trying to access something from a different class, but I am not sure how to pass that information to the thread. Any suggestions would be appreciated.

open class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

    val threadWithRunnable = Thread(datarun())

class datarun: Runnable, MainActivity() {
override fun run() {
while (true) {
findViewById( {
text = “First”}
findViewById( {
text = “Second”}
} }}

When an android app crashes, the stack trace can be found in logcat: Write and View Logs with Logcat

Your issue appears to be trying to modify a View from a background thread which is not allowed. You need to switch back to the main thread to update your UI. Here’s a guide on that: Communicate with the UI thread

Something that can really help simplify asynchronous code is coroutines. If you want to take a look, here’s the guide: Coroutines Guide

1 Like

For the coroutines, you could also check Googles code lab and I found this coroutines-serie on medium also helpful.