Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Toast Messages not working

I'm developing a game via Andengine for Android. I have MainActivity class and GameScene class. I use Toast messages in GameActivity. And it is working.

Toast.makeText(this, " Hello World", Toast.LENGTH_SHORT).show();

So I wanna use Toast messages in GameScene class. But it doesn't work. Here is the code:

Toast.makeText(activity, " Hello World", Toast.LENGTH_SHORT).show();

I have to use "activity" instead of "this". But it doesn't work

why?

EDITED:

when I use second one, an error occurs. LogCat: http://s29.postimg.org/k8faj9mdj/Capture.png

like image 487
user3076301 Avatar asked Dec 19 '13 09:12

user3076301


People also ask

Why is toast not showing messages?

Make sure not to forget to call show() after the makeText. Check for the Context , if its the right one. The most important one , make sure your Android Notifications are on for your app, else the Toast will not be shown.

Why is my toast not showing Android?

If everything looks fine, yet no Toast displayed then check the Android OS version you're running the App. Note : When the Notification is disabled, Apps will not display any notification on Notification bar also it will not display any Toast messages for that app.

How do you toast a message?

Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.


2 Answers

You're trying to display a Toast in a background thread. You should do all your UI operations on the main UI thread.

The exception RuntimeException: Can't create handler inside thread that has not called Looper.prepare() can be a little cryptic for beginners but essentially it tells you that you're in a wrong thread.

To solve it, wrap the toast to e.g. runOnUiThread():

activity.runOnUiThread(new Runnable() {
  @Override
  public void run() {
    Toast.makeText(...).show();
  }
});
like image 71
laalto Avatar answered Sep 19 '22 14:09

laalto


There could be two reasons for your code to not work. It's ether your activity parameter is null or...

Short time after you showing the toast the activity is die, in that case it will kill the toast as well, to avoid this you can call activity.getApplicationContext() like in @Mehmet Seçkin answer.

like image 42
Ilya Gazman Avatar answered Sep 19 '22 14:09

Ilya Gazman