In Android programming, what exactly is a Context
class and what is it used for?
I read about it on the developer site, but I am unable to understand it
Just putting it out there for newbies;
So First understand Word Context :
In english-lib. it means:
"The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood and assessed."
"The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning."
Now take the same understanding to programming world:
context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)
You can get the context by invoking getApplicationContext()
, getContext(), getBaseContext()
or this
(when in the activity class).
To Get Context Anywhere in application use following code:
Create new class AppContext
inside your android application
public class AppContext extends Application {
private static Context context;
public void onCreate(){
super.onCreate();
AppContext.context = getApplicationContext();
}
public static Context getAppContext() {
return AppContext.context;
}
}
Now any time you want application context in non-activity class, call this method and you have application context.
Hope this help ;)