Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a Toast message in from a class that doesn't extend Activity [duplicate]

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.

like image 332
user1513889 Avatar asked Jul 13 '12 08:07

user1513889


2 Answers

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();
  }
like image 75
Blackbelt Avatar answered Oct 08 '22 17:10

Blackbelt


---------------------- 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...

like image 25
MobileEvangelist Avatar answered Oct 08 '22 19:10

MobileEvangelist