12

I just learned that I can use either:

Toast.makeText(MainActivity.this, R.string.some_string,Toast.LENGTH_SHORT).show();

or,

Toast.makeText(getApplicationContext(), R.string.some_string,Toast.LENGTH_SHORT).show();

To display a Toast in Android.

Earlier I thought context was actually a sort of handle to the parent window where it should be display but the documentation is unclear about this.

Then I came across this table: enter image description here

It also doesn't seem to mention what context exactly to use for a Toast?

Edit:

Is context like a "handle to parent window" for the sub-window like Toast? or does it actually allow the Toast.makeText to get access to resources or something?

Why is it being used at all if the context doesn't matter?

user963241
  • 6,758
  • 19
  • 65
  • 93

4 Answers4

2

Looking at Toast.java, I can see the Context is used only for:

  • obtaining Resources
  • obtaining Package Name
  • getText which is actually same as #1

So apparently there's no difference whether it's Activity or ApplicationContext, unless those resources depend on theme (which is not the case as far as I can tell).

And no, the context passed to Toast is not a handle to parent window in any sense.

ernazm
  • 9,208
  • 4
  • 44
  • 51
1

I'd recommend to use the activity in your case. Since you're calling from the activity itself. The activity is a Context and you're using the method on the activity to get another context (the application). It is a little unnecessary.

However in the case you're calling a toast from somewhere else it might be a better idea to use the application, since the application will always be there while your app is active.

Vuong Pham
  • 1,852
  • 1
  • 8
  • 6
0

You can show Toast only from UI (main thread) context. If you want show this from Service (but this is contradicts Google guidelines), you can do this way: Show toast at current Activity from service

Community
  • 1
  • 1
Alex
  • 617
  • 4
  • 15
0

For toasts, which are short-lived, you can usually use whatever context you want. Typically, you would use the activity context, but application context is fine as well.

Josh Kitchens
  • 1,080
  • 11
  • 18