Thursday 8 January 2015

What is the difference between this context and getapplicationcontext ? 

There are two types of contexts available in android to create any component. 
1. this context (or) this pointer 
2. application context When programmer wants to create any component or control,
 then you have to use one of the contexts. 
 eg: TextView t = new TextView(this); Here we are using this pointer (context). 
 eg: static TextView st = new TextView(getApplicationContext()); 
 Here we are using application context, because it is a static variable whose life time will be through out application life time.

 If you use this pointer here, then it will leak memory (memory wastage) of your activity. 



  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. 

  ContextWrapper.getBaseContext()

  If you need access to a Context from within another context, 
  you use a ContextWrapper..
  The Context referred to from inside that ContextWrapper is accessed via  getBaseContext().

No comments:

Post a Comment