3

I want to store the application context in a static member, like this, so I can access it, the shared preferences, resources etc. everywhere.

My question is whether the context can change itself during the application lifetime, so the stored context won't work in a proper way and I can't access shared preferences etc.

Or is the context immutable, so I can use it without any doubt?

Thanks for you answers!

Community
  • 1
  • 1
JaMic
  • 171
  • 5

4 Answers4

1

Application context stays unaltered during application lifetime.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

Context is immutable during all work of app. And you can use it in static way to get resources, shared preferences, etc.

Artyom Kiriliyk
  • 2,513
  • 1
  • 17
  • 21
0

When you look at the accepted answer of this post, you will find that it is Ok to do this, but handle with care...

There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.

In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, if you pass the application Context into the LayoutInflator you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks.

Community
  • 1
  • 1
Frank
  • 16,476
  • 7
  • 38
  • 51
0

Yep, you can use it with shared preferences and get resources etc.

getApplicationContext() function should do it. It shouldn't matter if its mutable.

I'LL BE BACK
  • 155
  • 2
  • 7