Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 676
michael Avatar asked Oct 06 '10 17:10

michael


People also ask

What is looper prepare?

android.os.Looper. Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

What is looper message and handler?

Looper is a worker that keeps a thread alive, loops through MessageQueue and sends messages to the corresponding handler to process. Finally Thread gets terminated by calling Looper's quit() method.

What is UI thread in Android?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.

What is a handler in Android?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .


1 Answers

You need to call Toast.makeText(...) from the UI thread:

activity.runOnUiThread(new Runnable() {   public void run() {     Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();   } }); 

This is copy-pasted from another (duplicate) SO answer.

like image 186
Jacob Marble Avatar answered Sep 30 '22 06:09

Jacob Marble