CalledFromWrongThreadException (メインスレッド以外から、UIの更新)
問題
Android のプログラミング中に以下の例外が発生。
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
どうも、UIを実装しているスレッド以外のスレッドから、UIに更新をしようとしている時に発生しているよう。
原因
Android の制約らしい。
回避策
Handler のインスタンス経由で、別スレッドからメインスレッドに更新を依頼すれば良いらしい。
メインスレッド内で、Handler のインスタンスを生成。
val handler = Handler()
他のスレッド内で、handler.post に処理を渡してあげる。
thread { handler.post( Runnable() { val resultView: TextView = findViewById(R.id.result) resultView.text = "test" }) }
この場合、メインスレッドが画面の更新を担うことになるので、Android の制約に反せず、例外は発生しない。