Baruch
Baruch

Reputation: 1636

How do I use Toast notification properly on android?

I can't seem to be able to use the toast notification properly. In all of my other apps it worked great but in this one it doesn't. In this app I started using openGL with a framework from a book named "Beginning Android Games" and now I don't seem to be able to use the toast notification. I have no idea what to do... It fails because of the context. How can I make a context that will work? Please help me! this is part of my code because the code is too long:

private void updateReady() {
Coin.number = 0;
if (game.getInput().getTouchEvents().size() > 0) {
    state = GAME_RUNNING;
    Coin.number = 0;
    Num.number = 0;

    Toast.makeText(this, "Start!", Toast.LENGTH_SHORT).show();
    }
}

When I put the line:

    Toast.makeText(this, "Start!", Toast.LENGTH_SHORT).show();

in the class that extends Activity and run it it just doesn't do anything... I tried to make it into a method and call it from other classes but it got a force close...

Upvotes: 0

Views: 4778

Answers (4)

derfshaya
derfshaya

Reputation: 338

I assume you're working with this framework called "Beginning Android Games 2".

According to this code, the instance variable you need here is glGame, which is a GLGame object. It extends Activity, so you can just do this:

Toast.makeText(glGame, "Start!", Toast.LENGTH_SHORT).show();

Upvotes: 0

Joakim
Joakim

Reputation: 1

Maybe this helps.

I had class defined like this

    public class tutorialThree extends Activity implements View.OnClickListener

I tried to use Toast like this

    Toast.makeText(this, "Wallpaper set", Toast.LENGTH_SHORT).show();

Did not work, because my class implements that interface "View.OnClickListener" (or whatever it is :)) So toast gets confused with "this" reference, you have to be more precise, so add name of your class before "this" keyword, like this:

    Toast.makeText(tutorialThree.this, "Wallpaper set", Toast.LENGTH_SHORT).show();

This solved my problem, now i can see toast.

Upvotes: 0

Amos M. Carpenter
Amos M. Carpenter

Reputation: 4958

You could always make your application context, or the context of whatever activity you're starting your GameScreen from, available statically or by passing it as an argument from whatever creates your instance.

Having said that, though, beware of memory leaks!

Upvotes: 0

Cody Caughlan
Cody Caughlan

Reputation: 32748

You can try using getApplicationContext() to get a reference to the current Activity context

Upvotes: 1

Related Questions