tags:

views:

113

answers:

3

Hi,

Can anyone tell me what's exctly a Context class in android and whats the need of this in android prgramming.. I read about this in developer site.., but unable to understand it clearly.. please help me . Thanks

+4  A: 

Putting it simply:

As the name suggests, its the 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).

Typical use of context:

  • Creating New objects: Creating new views, adapters, listeners:

    TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),..);

  • Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

    context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(name, mode);

  • Accessing Components Implicitly: Regarding content providers, broadcasts, intent

    getApplicationContext().getContentResolver().query(uri,...);

Sameer Segal
A: 

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An android app has activities. It's like a handle to the environment your application is currently running in. The activity object inherits the Context object.

For more information look here at Section 1.3

giulio
+2  A: 

An Android Context is an "interface" that allows access to application specific resources and class and information about application environment.

If your android app was a web app, your context would be something similar to ServletContext ( I am not making an exact comparison here)

Your activities and services also extend Context to they inherit all those methods to access the environment information in which the app is running.

naikus