Search code examples
androidandroid-contexttoastandroid-toast

Toast: Docs' tutorials say to use getApplicationContext, but Docs References say to use getApplication or getActivity


https://developer.android.com/guide/topics/ui/notifiers/toasts: in the sources examples, they use getApplicationContext.

https://developer.android.com/reference/android/widget/Toast.html#makeText(android.content.Context,%20int,%20int): "Context: The context to use. Usually your Application or Activity object.".

What should we use in definitive?

To answer this question, I think one should think about...:

  • The lifecycle of the object Toast defined in a fragment, and then the lifecycle of Toast defined in an activity
  • The risk of memory leaks if we use getActivity, which depends on the Toast

https://blog.mindorks.com/understanding-context-in-android-application-330913e32514: here, it seems that one should use getActivity for Toast.


Solution

  • What should we use in definitive?

    Generally speaking: if the Context is being applied to something for the UI, use the Activity, so that your current theme can be taken into account. Toast is UI; therefore, use the Activity.

    In reality, I don't think that a Toast necessarily uses anything from the theme.

    The lifecycle of the object Toast defined in a fragment, and then the lifecycle of Toast defined in an activity

    Those are the same thing, since a fragment is unrelated to a Toast. You do not pass a Fragment to any method on Toast.

    The risk of memory leaks if we use getActivity, which depends on the Toast

    Since the Toast is short-lived, any possible leak is short-lived. Leaks are a problem when the leaked material is referenced for an indefinite period of time and so will not get cleaned up.