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:
// Set this up in the UI thread. mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message message) { // This is where you do your work in the UI thread. // Your worker tells you in the message what to do. } }; void workerThread() { // And this is how you call it from the worker thread: Message message = mHandler.obtainMessage(command, parameter); message.sendToTarget(); }
Other options:
You could use Activity.runOnUiThread()
. Straightforward if you have an Activity
:
@WorkerThread void workerThread() { myActivity.runOnUiThread(() -> { // This is where your UI code goes. } }
You could also post to the main looper. This works great if all you have is a Context
.
@WorkerThread void workerThread() { ContextCompat.getMainExecutor(context).execute(() -> { // This is where your UI code goes. } }
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.