Reputation: 171
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!
Upvotes: 3
Views: 386
Reputation: 155
Yep, you can use it with shared preferences and get resources etc.
getApplicationContext() function should do it. It shouldn't matter if its mutable.
Upvotes: 0
Reputation: 2513
Context is immutable during all work of app. And you can use it in static way to get resources, shared preferences, etc.
Upvotes: 1
Reputation: 15641
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.
Upvotes: 0
Reputation: 75629
Application context stays unaltered during application lifetime.
Upvotes: 1