3

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();
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
  • see http://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon and http://stackoverflow.com/questions/16141369/difference-between-getapplicationcontext-and-classname-this – Shayan Pourvatan May 17 '14 at 05:42

2 Answers2

2

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.

Vikalp Patel
  • 10,082
  • 6
  • 55
  • 92
  • how do u become such an expert in android programming .i am difficult having trouble with understanding programs itself.any tip for a noob to become more like you – sweet_revathy569 Jun 04 '14 at 16:23
2

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

Community
  • 1
  • 1
kablu
  • 569
  • 1
  • 6
  • 25