-3

I use this code in all my app fragments and it should be better if I use a static method. How can I do it? This static method should also works on fragment, not only activities.

My not static showToast method:

public void showToast(String msg){
    Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

SOLVED BY USING THIS STATIC METHOD thanks @KishanDhamat

public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();

}

Hasta'98
  • 184
  • 2
  • 9
  • 2
    Well what activity would you expect `getActivity()` to return if you're calling this from a static method? (Also note that following Java naming conventions, this should be `showToast`.) – Jon Skeet May 02 '14 at 08:34
  • But that method it is not static, I call it every time in my fragments. By the way I have edited the main question – Hasta'98 May 02 '14 at 08:43
  • see my edits for answer. – Kishan Dhamat May 02 '14 at 08:47

3 Answers3

5

Use this:

public static void showToast(Context context, String text) {
    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}

now for calling this method you should call like this:

ClassName.showToast(context,"text");

Here classname is class that containing static method.

Kishan Dhamat
  • 3,746
  • 2
  • 26
  • 36
3
  • Change the signature of the method and add given Context as parameter
  • Change the signature of the method to make it static
  • Pass the Context as first argument of your Toast.makeText call
Mena
  • 47,782
  • 11
  • 87
  • 106
0
public static void changeActivity(Context context,Class that){
    context.startActivity(new Intent(context, that));
} // my static method

  public void forgotPass(View view){
    Function.changeActivity(LoginActivity.this,ForgotPass.class);
} // my activity i want to change

This is my solution, hope it can help

MindVN
  • 91
  • 2
  • 3