What does the following exception mean; how can I fix it?
This is the code:
Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);
This is the exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast.<init>(Toast.java:68)
at android.widget.Toast.makeText(Toast.java:231)
You’re calling it from a worker thread. You need to call
Toast.makeText()(and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.Look up Communicating with the UI Thread in the documentation. In a nutshell:
Other options:
You could use
Activity.runOnUiThread(). Straightforward if you have anActivity:You could also post to the main looper. This works great if all you have is a
Context.Deprecated:
You could use an AsyncTask, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it’s done.
It’s convenient, but can leak contexts if not used correctly. It’s been officially deprecated, and you shouldn’t use it anymore.