beans
beans

Reputation: 1765

Get context in Android?

I am inside a class inside my android app, how can I get the apps main context and activity?

Thanks for your help!

Upvotes: 1

Views: 37368

Answers (3)

lomza
lomza

Reputation: 9746

As @Robert mentioned, Context is an abstract class and what you have are structures:

Context < ContextWrapper < Application

Context < ContextWrapper < ContextThemeWrapper < Activity

Context < ContextWrapper < ContextThemeWrapper < Activity < ListActivity

Context < ContextWrapper < Service

Context < ContextWrapper < Service < IntentService

So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it elsewhere.

I explain the difference in contexts here.

Upvotes: 0

Robert
Robert

Reputation: 42819

I am sure you already have the context but you don't know that it is the context:

Context is an abstract base class a lot of classes are inherited from.

Therefore when ever the class you are writing code for is one of the following you have you context by using the this reference:

  • ContextWrapper
  • MockContext
  • AbstractInputMethodService
  • AccessibilityService
  • AccountAuthenticatorActivity
  • Activity
  • ActivityGroup
  • AliasActivity
  • Application
  • BackupAgent
  • BackupAgentHelper
  • ContextThemeWrapper
  • ExpandableListActivity
  • InputMethodService
  • IntentService
  • IsolatedContext
  • LauncherActivity
  • ListActivity
  • MockApplication
  • MutableContextWrapper
  • NativeActivity
  • PreferenceActivity
  • RecognitionService
  • RemoteViewsService
  • RenamingDelegatingContext
  • Service
  • SpellCheckerService
  • TabActivity
  • TextToSpeechService
  • VpnService
  • WallpaperService

Hence you can write:

Context context = this;

or

Context context = (Context) this;

Upvotes: 26

Raz
Raz

Reputation: 9058

If it's a custom view: there is a paramater context which is your activity.

Activity activity = (Activity)context;

If it's a different class just send the activity in the constrctor.

Upvotes: 1

Related Questions