9

I have a class that I am using to get GPS data within my activity. In the constructor I pass it the activity's context:

gpsFetcher = new GPSFetcher(this);

and in the gpsFetcher class I have:

this.context = c.getApplicationContext();

OR just

this.context = c;

and then I call the toast with:

Toast.makeText(context, "sometext", Toast.LENGTH_LONG);

But it never shows up... Is there something I'm missing? Is it possible?

Thanks!

Matt
  • 2,650
  • 4
  • 36
  • 46
  • 1
    Are you calling `Toast.show();`? If not, this is a duplicate of http://stackoverflow.com/questions/3466087/cannot-display-toast-from-an-activity-other-than-my-main-activity – Jess Apr 04 '11 at 20:21
  • No, see the answer below... Facepalm. Thanks. – Matt Apr 04 '11 at 20:27

4 Answers4

13

Are you forgetting Toast#show?

Toast toast = Toast.makeText(context, "sometext", Toast.LENGTH_LONG);
toast.show();
Matthew
  • 44,826
  • 10
  • 98
  • 87
  • 1
    DOH! Yeah, that's the problem... I even had put it in other places I just wasn't getting to them because I was stopping when this one didn't show up! Mondays... Thanks! – Matt Apr 04 '11 at 20:26
2

You must call show() as well:

Toast.makeText(context, "sometext", Toast.LENGTH_LONG).show();

nagyben
  • 938
  • 1
  • 10
  • 19
Hasid Mansoori
  • 171
  • 1
  • 1
  • 10
0

I have met the same question but I solved it.!! In the non-activity class , you just announce a "public static String". Then in your MainActivity or other activity , you can directly use Toast.

In my case , I declare a non-activity class NoteDB. so I declare public static String S in the class . (You can change S value in the class. Then in my MainActivity , I announce

Toast(MainActivity.this, NoteDB.S ,TOAST.SHORT_LENTGH).show();

It works well.

鄭元傑
  • 1,417
  • 1
  • 15
  • 30
0

To display a Toast in a Non-Activity Java class, add the Context in the constructor of the java class

[Here PrizeMethods is my java class]

public class PrizeMethods {
    Context context;
    public PrizeMethods(Context context) {
        this.context = context;
    }
   }

and where you are instancing this class in your activity (making an object of it, using it in your main activity), add the context as a parameter.

Like this:

 PrizeMethods pm=new PrizeMethods(this);

after that inside your java class, you can create a toast like this:

 Toast.makeText(context, "toast inside class!!", Toast.LENGTH_SHORT).show();