0

I was reading over the android documentation for toasts, and noticed that the example code uses getApplicationContext() rather than getActivity() or this. From the docs:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Based on other sources, I have been given to understand that using getApplicationContext() is generally bad practice. Are toasts somehow an exception? If so, why? Or are the Android docs just wrong in this case?

Community
  • 1
  • 1

3 Answers3

4

I have been given to understand that using getApplicationContext() is generally bad practice

I would describe it more as "use Application when you know why you are using Application". Too many Android developers have negligible Java experience, get confused by inner classes, and think that they need to call getApplicationContext() (or getBaseContext()) to get a Context to pass as a parameter to something or another.

Dave Smith's epic blog post on the role of different Context implementations covers a fair number of the common use cases... though Toast is not among them.

Are toasts somehow an exception? If so, why?

Toasts work with Application as the Context, though there is no particular need to use an Application to show a Toast.

Or are the Android docs just wrong in this case?

They are not wrong, insofar as the code works. The JavaDocs for Toast in various places point out that Activity is also a fine Context to use, and I see nothing in the Toast source code to indicate otherwise.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • +1 for the link (or will be when this account can +1). That blog post is truly useful in understanding all this stuff. However, I did some further testing based on the info in it, and it turns out that toasts created with Application context will use the default theme, ignoring any styling you set in your app. Arguably that means the example code doesn't "work", depending on what definition of "work" you use. –  Jun 24 '14 at 14:45
0

It's important to note that Toast can be used even when your context is not visible or is not in control of any UI. In other words, the documentation is pointing out that you can have a minimal context (like that from a service) and still use Toast.

I don't believe that the documentation is trying to present a "best practice" for the use of Context, but rather to properly demonstrate this attribute of Toast.

Jim
  • 10,172
  • 1
  • 27
  • 36
  • Accepted as I believe you are right about the intent of the docs. Although it is worth noting that toasts created with a minimal Context will ignore any app-specific styling. –  Jun 24 '14 at 13:55
0

I had a problem with Toast localization string when used application context. It worked properly with activity.

uberchilly
  • 159
  • 1
  • 7