Messages about Toast for Android do not work

I am developing a game through Andengine for Android. I have a MainActivity class and a GameScene class. I am using Toast posts in GameActivity. And it works.

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

So, I want to use Toast messages in the GameScene class. But that will not work. Here is the code:

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

I need to use "activity" instead of "this". But that does not work.

why?

EDITED:

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

+6
source share
7 answers

You are trying to display Toast in a background thread. You must perform all user interface operations in the main user interface thread.

RuntimeException: Can't create handler inside thread that has not called Looper.prepare() may be a little cryptic for beginners, but essentially it tells you that you are in the wrong thread.

To solve the problem, wrap the toast, for example. runOnUiThread() :

 activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(...).show(); } }); 
+21
source

There may be two reasons why your code does not work. This ether your activity parameter is null or ...

For a short time after you show the toast, the activity will die, in which case it will also kill the toast, to avoid this, you can call activity.getApplicationContext() , as in @Mehmet SeΓ§kin's answer.

+1
source

use one of the following

 Toast.makeText(getApplicationContext(), " Hello World", Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(),"please Create your Account First", Toast.LENGTH_SHORT).show(); Toast.makeText(GameActivity.this,"please Create your Account First", Toast.LENGTH_SHORT).show(); 
+1
source

Using:

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

or

 Toast.makeText(activity.this, " Hello World", Toast.LENGTH_SHORT).show(); 
0
source
 Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_SHORT).show(); 

try it.

0
source

Since you asked why; I think you are giving an activity reference as a Toast message context, so it does not work.

If you are trying to show a Toast message from out of action, you can try:

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

or from GameActivity

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

or from MainActivity

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

Since you are calling it from a class. you need to get the context from the action through the class constructor, otherwise you need to use GetApplicationcontext ().

0
source

All Articles