[Android] RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Tue, June 25, 2013 - 2 min read

開発中の Android アプリが、下記のエラーでクラッシュしました。

RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

原因は、doInBackground() 内で UI に関する処理を行なっていたためでした。 (具体的には、エラーメッセージを Toast で表示しようとしていた)

エラーが発生したときは、doInBackground() 内でエラーダイアログの表示などは行わず return null を返して、 onPostExecute メソッド内で良しなにエラー通知をするべきです。

メソッドdoInBackgroundはUIスレッドとは別なプールから取得されたスレッド上で実行されるのでGUI操作をしてはならない。代わりにUTスレッドと同期されるonProgressUpdateやonPostExecuteメソッド内でGUI操作を完了できる。

[引用]:バックグラウンドスレッドでダイアログを生成してはいけない - Kazzzの日記

[参考]

Android Can’t create handler inside thread that has not called Looper.prepare() - Stack Overflow

android - Can’t create handler inside thread that has not called Looper.prepare() - Stack Overflow