Displaying a Toast message from the Application class

Viewed 20040

I have several classes in my application. Some are Activities, Services and Pure java classes. I know i can display a Toast message from within an Activity but i'd like to display a Toast from a pure java class.

In the java class i pass a context in to the constructor but this doesn't seem to show the toast.

I have created a method in the Application class that takes a String as an argument, hoping i could generate a Toast using the Application context, no joy here either.

How can i generate a Toast from a class that isn't a service or Activity etc.

public class LoginValidate{

public LoginValidate(Context context) {

        this.context = context;

        nfcscannerapplication = (NfcScannerApplication) context
                .getApplicationContext();


    }

public void someMethod(){

nfcscannerapplication.showToastMessage(result);

}

}

.

///then in my Application class

public void showToastMessage(String message){

            Toast.makeText(this.getApplictionContext(), "Encountered a problem with sending tag: " + message, Toast.LENGTH_LONG).show();

    }
7 Answers

It worked for me with :

Toast.makeText(this.getContext(), R.string.title, Toast.LENGTH_LONG).show();

Need to pass the context to the showToastMessage(String message)

Like this showToastMessage(String message, Context context)

//then in my Application class

public void showToastMessage(String message, Context context){

            Toast.makeText(context, "Encountered a problem with sending tag: " + message, Toast.LENGTH_LONG).show();

    }

Pass the message from other class using function parameter

public void showToast(String message) {

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

}

Related