Android only the original thread that created the view

Only the original thread that created a view hierarchy can touch its views

Fix Android CalledFromWrongThreadException

In this tutorial, we shall learn to fix Android Exception CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views.

You might have come across this error while from a thread you are trying to set some property of a View or extract some property of a View, that belong to UI thread.

An important point to be remembered while trying to do any operations with UI views is that, only UI thread that created a view hierarchy can touch its views.

Following is simple example, where we try to access a TextView (that belong to UI thread) in another thread.

MainActivity.kt

You might see below exception in Logcat

Following is the line of code that caused this exception

In general, you touched an UI View from another thread, which you should not do without any help.

To fix this error, wrap the code that has to be executed on UI thread in a Runnable instance passed to runOnUiThread() method.

Following is the corrected MainActivity.kt

MainActivity.kt

Conclusion

In this Kotlin Android Tutorial, we have learnt how to fix Android Exception CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views.

Источник

Читайте также:  Blocked text on android
Оцените статью