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 kotlin

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.

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 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 kotlin. Фото Only the original thread that created a view hierarchy can touch its views kotlin

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.

Android «Только исходный поток, создавший иерархию представлений, может касаться его представлений».

Я построил простой музыкальный проигрыватель в Android. Представление для каждой песни содержит SeekBar, реализованный следующим образом:

Но эта последняя строка дает мне исключение:

Вы должны переместить часть фоновой задачи, которая обновляет пользовательский интерфейс, в основной поток. Для этого есть простой фрагмент кода:

Просто вложите это в метод, работающий в фоновом режиме, а затем скопируйте и вставьте код, который реализует любые обновления в середине блока. Включите только наименьшее возможное количество кода, иначе вы начнете побеждать назначение фонового потока.

Мое решение этого:

Вызовите этот метод в фоновом потоке.

ProgressBar.setProgress() имеет механизм, который он всегда будет выполнять в основном потоке, поэтому он работал.

Я был в этой ситуации, но я нашел решение с помощью объекта Handler.

Только исходный поток, создавший иерархию представлений, может касаться его представлений.

Возможно решить проблему с Объектом Обработчика.

Ниже приведены различные части моего кода:

Вы можете использовать Handler для удаления вида, не нарушая основной поток пользовательского интерфейса. Вот пример кода

Я вижу, что вы приняли ответ @ провидения. На всякий случай, вы также можете использовать обработчик тоже! Сначала сделайте поля int.

Затем создайте экземпляр обработчика как поле.

Наконец, поместите это в onCreate() метод.

У меня была похожая проблема, и мое решение некрасиво, но оно работает:

Используйте этот код, и не нужно runOnUiThread функционировать:

Это явно выдает ошибку. В нем говорится, какой поток создал вид, только тот, который может касаться его. Это потому, что созданный вид находится внутри пространства этого потока. Создание представления (GUI) происходит в потоке пользовательского интерфейса (основного). Таким образом, вы всегда используете поток пользовательского интерфейса для доступа к этим методам.

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 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 kotlin. Фото Only the original thread that created a view hierarchy can touch its views kotlin

На рисунке выше переменная прогресса находится внутри пространства потока пользовательского интерфейса. Таким образом, только поток пользовательского интерфейса может получить доступ к этой переменной. Здесь вы получаете доступ к прогрессу через новую Thread (), и именно поэтому вы получили ошибку.

Работа с пользовательским интерфейсом onPostExecute решает мою проблему.

Сопрограммы Kotlin могут сделать ваш код более кратким и читабельным, например:

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

Comments

AkilLis commented Sep 21, 2017

This «Only the original thread that created a view hierarchy can touch its views» error given after react native version upgrade 44.2 to 47.2.

Environment:
OS: ubuntu 16.04
Node: 6.10.0
npm: 3.10.10
Watchman: 4.7.0
Android Studio: 2.3 AI-162.4069837

Packages: (wanted => installed)
react-native: 0.44.2 => 0.47.2
react: 16.0.0-alpha.12 => 16.0.0-alpha.12

Target Platform: Android (6.0.0)

The text was updated successfully, but these errors were encountered:

hramos commented Sep 21, 2017

Hey, thanks for reporting this issue!

It looks like your description is missing some necessary information, or the list of reproduction steps is not complete. Can you please add all the details specified in the template? This is necessary for people to be able to understand and reproduce the issue being reported.

I am going to close this, but feel free to open a new issue that meets the requirements set forth in the template. Thanks!

jhalborg commented Oct 17, 2017

I second this. Using Expo SDK 21 along with TypeScript 2.5, and getting consistent crashes on recompilation each time on Android.

I found my issue by viewing the stacktrace I could send to the dev (through the Android report bug feature). It was due to the following call:

By turning off the Inspector module (for FPS perf etc), Expo stopped crashing.

ThaJay commented Oct 19, 2017 •

same problem, crashes on reload when perf monitor is visible.

ephor commented Nov 13, 2017

Also have this error on React-native 0.50.3 and android 8

ThaJay commented Nov 14, 2017

yimiIO commented Nov 22, 2017

@hramos
same question,
I quick repeat click one button on Android, it will show my toast repeat, in a minute, crash.
ndroid.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7361) at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1156) at android.view.View.requestLayout(View.java:19841) at android.view.View.requestLayout(View.java:19841) at android.widget.TextView.checkForRelayout(TextView.java:7688) at android.widget.TextView.setText(TextView.java:4585) at android.widget.TextView.setText(TextView.java:4442) at android.widget.TextView.setText(TextView.java:4417) at com.xsl.kit.utils.ToastWrapper.updateToast(ToastWrapper.java:61)

Venryx commented Dec 7, 2017 •

I also have this issue, with Android 7, and:

It is fixed when I disable the performance-monitor overlay. (so seemingly a bug in react-native)

Only the original thread that created a view hierarchy can touch its views. Exception occurs when _trd1 starts

Exception occurs when _trd1 starts. Why it is giving an exception. I have an imageView on which i have set an Animation. Same as i did on _imageCard2 they working both fine. but when i added a new thread it gives an exception after its completion.

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 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 kotlin. Фото Only the original thread that created a view hierarchy can touch its views kotlin

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You’re trying to modify UI components from a thread different than the UI thread.

Consider using a Handler with your thread.

You can also do your background processing in an AsyncTask which has ways to update the UI.

Edit: Some explanation:

UI = User Interface.

Your activity runs in a main thread which is the UI thread.

You’re not allowed to modify UI components (Buttons, ImageViews, etc.) except from the UI thread.

When you created your trd1 thread you attempted to modify an ImageView from it. That’s why you got the error.

runOnUiThread() is one of the methods you can use to make the modifications happen on the UI thread rather than your newly created thread.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *