Home » Android » android – How do I make a toast from a non activity class?

android – How do I make a toast from a non activity class?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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!

How to&Answers:

Are you forgetting Toast#show?

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

Answer:

You must call show() as well:

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

Answer:

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.