W/System.err: java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
时间: 2024-04-29 08:24:17 浏览: 418
This error occurs when you try to display a Toast message from a thread that is not the main UI thread. To display a Toast message, you need to call the Looper.prepare() method on the thread and then call the Toast.makeText() method to create and show the Toast message. Here's an example:
```
new Thread(new Runnable() {
@Override
public void run() {
// Do some background work
// ...
// Show a Toast message
Looper.prepare();
Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
```
In this example, we create a new thread and run some background work. Then, we call Looper.prepare() to prepare the thread for displaying the Toast message. We create the Toast message using Toast.makeText() and show it using the show() method. Finally, we call Looper.loop() to start the message loop and display the Toast message.
By calling Looper.prepare() and Looper.loop() on the thread, we ensure that the message loop is running and ready to handle the Toast message. This prevents the "Can't toast on a thread that has not called Looper.prepare()" error from occurring.
阅读全文