Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which context to use for Toast in Android?

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?

like image 640
user963241 Avatar asked Jun 16 '16 14:06

user963241


People also ask

What is context in toast Android?

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.

What is toast context?

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.

Which method is used to create a toast in Android?

The Toast. makeText() method is a pre-defined method which creates a Toast object. Parameters: This method accepts three parameters: context: The first parameter is a Context object which is obtained by calling getApplicationContext().

Which method is used to display toast?

Here is an Android Toast example: Toast toast = Toast. makeText(getApplicationContext(), "This is a message displayed in a Toast", Toast. LENGTH_SHORT); toast.


2 Answers

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.

like image 196
ernazm Avatar answered Oct 21 '22 19:10

ernazm


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.

like image 1
Vuong Pham Avatar answered Oct 21 '22 20:10

Vuong Pham