0

I am new to Android development and Software development too. I keep seeing this term called - 'context' in Android code. I know that it's a class in android.content package, but I don't understand what exactly is it and why is it needed in so many places, especially in the constructors.

Can someone please explain this term to me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ankit
  • 203
  • 1
  • 2
  • 6
  • possible duplicate of [Please explain me Context class in Android](http://stackoverflow.com/questions/2870678/please-explain-me-context-class-in-android) – Mat Jul 14 '11 at 05:09

1 Answers1

1

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,...);

Its copy from here

Community
  • 1
  • 1
Chirag
  • 56,621
  • 29
  • 151
  • 198