4

I want to create a global shortToast and longToast method to use it dynamically in all other activities I have, so I don't have to define the Toast method in every activity.

I've tried this, but Android Studio tells me that this is a memory leak:

public static Activity thisActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    thisActivity = this;    
}

public static void shortToast()
{       
  Toast.makeText(thisActivity, "message" , Toast.LENGTH_SHORT).show();
}

public static void longToast()
{       
  Toast.makeText(thisActivity, "message" , Toast.LENGTH_LONG).show();
}

What can I do instead to achieve this goal having a global toast method (without memory leak)?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
AlexioVay
  • 4,338
  • 2
  • 31
  • 49

2 Answers2

4

Create a Utils class:

public class Utils {

    public static void showToast(String msg, Context ctx) {
        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
    }
}

use it from Activity:

Utils.showToast("Message", this);

From Fragment:

Utils.showToast("Message", getActivity());
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
2

Pass the Activity as a parameter to shortToast() and longToast().

Or, put these methods in a subclass of Activity, and have all your activities inherit from it. Then, you can get rid of the static keyword from the methods and the thisActivity field, and simply use this.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491