juanhl
juanhl

Reputation: 1170

Are there different Android contexts?

I thought that Android context work as a singleton object which you access from differents ways.

However, in my project, I've created a simple Spinner using a simple ArrayAdapter in an nested AsyncTask (onPostExecuteMethod) in my MainActivity and I saw that it works different using getApplicationContext() and MainActivity.this.

  1. Text white with -> getApplicationContext()
  2. Text dark with -> MainActivity.this

Can you explain me that?

Upvotes: 0

Views: 85

Answers (2)

Philippe Banwarth
Philippe Banwarth

Reputation: 17725

The Context obtained from getApplicationContext() does not implement everything an Activity does, specially things related to UI, Themes, ...

The most complete explanation I have seen so far : Context, What Context?

Basically :

  • Use the Activity for everything related to the UI.
  • Use the application context for anything that can live longer than the Activity.

Upvotes: 2

pdegand59
pdegand59

Reputation: 13019

Every Context are related to the application context, each activity has it's own sub-context that will live with the activity (and will be destroyed with the activity).

In your example, you have different rendering depending on the context you use because Activities use ContextThemeWrapper if they have been assigned a theme (programmatically or in manifest).

You probably have a dark theme in your application but a light theme for the activity.

Upvotes: 3

Related Questions