user3396442
user3396442

Reputation: 67

Toast works fine in main Activity but not in a class

Using Toast in the MainActivity works fine

Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();

but when I use it in a class, getApplicationContext(), gets red lined and it does not work. How can I make it work in a class?

Upvotes: 0

Views: 831

Answers (2)

Raghunandan
Raghunandan

Reputation: 133580

You need to pass the context from Activity to the non Activity class and use the same there

  new NonActivityClass(ActivityName.this);

Then

 COntext mContext;
 public NonActivityClass(Context context)
 {
     mContext =context;
 }

Then

 Toast.makeText(mContext, "Button is clicked", Toast.LENGTH_LONG).show();

Note : Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself) to avoid memory leaks.

Upvotes: 5

Sekhar Madhiyazhagan
Sekhar Madhiyazhagan

Reputation: 889

If you want to get toast from class , you should send context to your class.

Upvotes: 0

Related Questions