Show Toast from static method in Android

I want to show a toast on the screen when a certain condition is met in my static method, as shown below:

public static void setAuth(String a) { String[] nameparts1; if (a.trim().isEmpty()) { author = "Author Name"; firstinit1 = "Initial"; surname1 = "Surname"; } if (a == 'X') { Toast ifx = Toast.makeText(getApplicationContext(), "Please enter name in correct format.", Toast.LENGTH_SHORT); ifx.show(); } } 

However, this gives me an error: "It is not possible to make a static reference to the non-static getApplicationContext () method from the ContextWrapper type."

Hope I have provided enough information here. Any help would be greatly appreciated!

+4
source share
2 answers

Pass the context as a parameter (in the call, use getApplicationContext () as input) and in the static function use the context:

 public static void setAuth(String a, Context context) { ... Toast ifx = Toast.makeText(context, "Please enter name in correct format.", Toast.LENGTH_SHORT); ... } 

And in the function call

 setAuth("Some String",getApplicationContext()); 
+15
source

you must pass the context as a parameter to your method

 public static void dialog(boolean value, Context context) { if (value) { Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } } 
0
source

Source: https://habr.com/ru/post/1493037/


All Articles