Which context to use for Toast in Android?
Asked Answered
C

4

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?

Cythiacyto answered 16/6, 2016 at 14:25 Comment(2)
the Activity's context. For the ui use always the activity's contextRaffaello
take a look at here https://mcmap.net/q/35856/-difference-between-getcontext-getapplicationcontext-getbasecontext-and-quot-this-quotGrosgrain
I
3

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.

Ideo answered 8/2, 2019 at 13:27 Comment(0)
B
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.

Blinding answered 16/6, 2016 at 14:36 Comment(0)
D
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

Doak answered 16/6, 2016 at 14:27 Comment(1)
Google used application context: developer.android.com/guide/topics/ui/notifiers/toasts.htmlCyclops
M
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.

Mielke answered 16/6, 2016 at 14:28 Comment(1)
Yes, this makes sense. Please review my question for an edit.Cythiacyto

© 2022 - 2024 — McMap. All rights reserved.