14

Possible Duplicate:
How do I make a toast from a non activity class?

How can I create and show a Toast message from a class which does not extended the Activity class? I'm using this class in another class that is extended by Activity.

Community
  • 1
  • 1
user1513889
  • 211
  • 1
  • 3
  • 5

2 Answers2

17

You need a context Reference. Just have a helper method like

  public static void showToastMethod(Context context) {
        Toast.makeText(context, "mymessage ", Toast.LENGTH_SHORT).show();
  }
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • my method which use to show toast in try catch block is static – user1513889 Jul 13 '12 at 08:37
  • 3
    This seems like a great way to leak a context. Rather pass the context as an argument to `showToastMethod()` and use it from there. Holding a permanent reference to it can be bad if an instance of your class lives longer than the activity/service/.. to which the context belongs. Making that reference static doesn't make it better, rather worse. –  Jul 13 '12 at 09:59
  • 1
    yes it is. It is a bit boring editing and re-editing in order to meet the requirement of a (not) customer – Blackbelt Jul 13 '12 at 10:05
5

---------------------- New Modular Version ------------------------

Create an Interface

 public interface ShowToast {
      public onShowToast (String message); [additionally you can pass toast duration]
}

In Activity class, implement this interface and write Toast method to show message.

public class ActivityClass extends Activity implements ShowToast{

  public giveCallToNonActivityClass(){
     new NonActivityClass(this); //Here we're passing interface impl reference.
  }

  public onShowToast (String message) {
        Toast.makeText(ActivityClass.this, message, Toast.LENGTH_SHORT).show();
  }
}

Sample NonActivityClass will look like:

public class NonActivityClass {

  public NonActivityClass (ShowToast interfaceImpl) {
       interfaceImpl.onShowToast("I'm calling Toast from Non Activity ");
  }
}

Earlier version was too old to refer. Hope this more modular approach help.

-------------------------------- Old Version 2012 ----------------------------

You can pass context of that activity to your class by passing value to nonActivity class

example:

new NonActivityClass(Activityclass.this) ;

and as in above answer

new MyClass(ActivityClass.this);

In NonActivityClass

public class NonActivityClass {

  public NonActivityClass (Context context) {

        Toast.makeText(context, "mymessage ", Toast.LENGTH_SHORT).show();
  }

}

Hope this works for you...

MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36