0

Just ironed out a bug in my Android app. I was trying to use getAssets() to pull a file from my assets directory. I subclassed Application and returned a "getApplicationContext" object so that all my classes can use a context whenever they need to.

But after much headache and NullPointerExceptions, it turns out that I needed to pass a local context variable and use THAT instead. If I use a global application context, getAssets doesn't work!

So why is this? What's so special about a local context variable that makes it work. I thought any old "Context" variable was enough to access the necessary methods and make them work properly!

Bhagwad Jal Park
  • 1,023
  • 1
  • 11
  • 20
  • 2
    See the answer from Commonsware to this question...http://stackoverflow.com/questions/7298731/when-to-call-activity-context-or-application-context In particular, the comment about why not to use `getApplicationContext()`... **It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.** and the associated link. – Squonk Jun 09 '12 at 23:40
  • Thank you - that is an excellent resource. – Bhagwad Jal Park Jun 10 '12 at 01:11

1 Answers1

0

A local context variable is also an Activity. The Activity provides extra functionality that the AssetManager, you call using getAssets(), uses. Android strictly uses contexts and not activities in order to avoid memory leaks. You should almost always use your Activity's context.

Zaid Daghestani
  • 8,285
  • 3
  • 30
  • 43