1

I paste some piece of my code here:

public void onCreate(Bundle savedInstanceState) {
        Log.e("Main Activity", "OnCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_frame);

        //GlowEffect is the custom class's constructor:GlowEffect(context);
        new GlowEffect2(getApplictionContext());

        AlertDialog.Builder builder = new Builder(this);
...
...

I find that when I change the param in **Builder(this)** to Builder(getApplicationContext()); The app will crash! While the GlowEffect2 constructor works well whatever the param is "this" or "getApplicationContext()". So what the difference between the two params?

1 Answer 1

3

As you've noticed, the constructor for Builder takes a Context object as argument.

The Activity and Application objects are both subclasses of Context, so either would be a valid parameter to create a Builder.

Object -> Context -> ContextWrapper -> Application
Object -> Context -> ContextWrapper -> ContextThemeWrapper -> Activity

What's the difference between an Application and an Activity? I think one of the most obvious differences is their life cycles:

  • The Activity will live for as long as that particular piece of UI is running, and will be destroyed and recreated in various situations, e.g. on an orientation change, or when the Activity is not being viewed and the Android OS needs to free some memory by destroying Activities that are not being viewed.

  • The Application will live for as long as the application itself is running.

As for your specific problem, what is the stack trace for the crash? This question says getApplicationContext() might be null because the application is still starting up whilst the Activity is being created (the answer says the issue was fixed in Android OS 1.6).

2
  • Thanks for your answer.Yeah,I also thought that maybe the "getApplicationContext()" was null,but why the "GlowEffect2(getApplicationContext())" was OK?!(PS:In GlowEffect2 I use Context in "TextView tv = new TextView(context)"). So I still dont understand why?
    – Rocky
    Commented Nov 1, 2011 at 6:08
  • You need to provide the stack trace from the crash, and tell us which line of the source code it points to. You should also add logs to print out getApplicationContext() at various stages to figure out when it is null. Maybe there is a timing issue that means getApplicationContext() exists by the time the GlowEffect2 code runs?
    – Dan J
    Commented Nov 1, 2011 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.