Getting the Application Context

The easiest way to get the application context is: Create a class App that extends android.app.Application public class App extends Application { public static Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); } } Modify your AndroidManifest.xml ‘s <application> tag to have the attribute android:name=”your.package.name.App”. Any time you need the application context, … Read more

Diffinitive rules for using Android’s getBaseContext, getApplicationContext or using an Activity’s “this”

The getBaseContext() is the method of ContextWrapper. And ContextWrapper is, “Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.” (as per javadocs) So this is used to delegate the calls to another context.

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an “interface” that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to … Read more

How to retrieve a context from a non-activity class?

This problem seem to arise a lot in Android development. One solution to obtaining a reference to a specific Context is subclassing the Application and grab a reference to the Context which you want. public class MyApplication extends Application { private Context context; @Override public onCreate() { super.onCreate(); this.context = getApplicationContext() // Grab the Context … Read more