Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Toast from within static method in Android

I wish to display a toast to the screen when a certain condition is met within my static method as shown below:

public static void setAuth(String a) {

    String[] nameparts1;

    if (a.trim().isEmpty()) {
        author = "Author's 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 the error: 'Cannot make a static reference to the non-static method getApplicationContext() from the type ContextWrapper'.

Hopefully I have provided enough information here. Any help would be much appreciated!

like image 490
petehallw Avatar asked Jul 23 '13 19:07

petehallw


People also ask

How do you show toast on android?

Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.

Which method is used to display toast?

Instantiate a Toast object Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.


2 Answers

Pass the context in as a parameter (in the call, use getApplicationContext() as the input) and in the static function, use 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());
like image 87
lcta0717 Avatar answered Oct 26 '22 10:10

lcta0717


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();

}
}
like image 30
Kaustubh Bhagwat Avatar answered Oct 26 '22 12:10

Kaustubh Bhagwat