sweet_revathy569
sweet_revathy569

Reputation: 83

What is the Difference between using getApplicationcontext() & this in Toast .maketext() method

Is there any specific instance where i have to use getApplicationcontext() or this in the context parameter of Toast.makeText() method

 Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();

 Toast.makeText(getApplicationcontext(), "HI", Toast.LENGTH_LONG).show();

Upvotes: 3

Views: 441

Answers (2)

kablu
kablu

Reputation: 669

You can follow

View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

"this" and getContext() both are same

[Reference] [Difference between getContext() , getApplicationContext() , getBaseContext() and “this”]1

Upvotes: 2

Vikalp Patel
Vikalp Patel

Reputation: 10887

getApplicationContext :

As per Developer documention : getApplicationContext

Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

Use:

You can use throughout your application with the help of getting Application context using

public class YourApp extends Application
{
 static YourApp appstate;
 public void onCreate(Bundle savedInstanceState){
    super.onCreate();
    appstate = this;
   }
 public static YourApp getApplication(){
    return appstate;
   }
}

How to use it : YourApp.getApplication();


this

Within an instance method or a constructor, this is a reference to the current object.

Use: You can use as along as you can see your Activity Context

e.g.

public void onCreate(Bundled savedInstanceState)
{
 ...
Toast.makeText(this, "HI", Toast.LENGTH_LONG).show();
}

How one can differentiate use of this and getApplicationContext() using Toast.makeText()?

Try to use Toast.makeText() in AynscTask with this and getApplicationContext.

Upvotes: 2

Related Questions