Search code examples
androidmethodsstatictoast

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!


Solution

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