I have a static Preferences class that hold some application preferences and stuff like that. Is it ok to store reference to ApplicationContext there? I need that reference so i can get cache folder and stuff like that in classes that don't inherit Activity.
You're right to use the ApplicationContext
there since if you don't it can cause significant memory leaks.
However, the problem you have is that the static
variable may not retain its value. Due to the way that Android handles applications it is possible that your application could be killed and then restarted - usually due to the user switching to other applications - in such a way that your static
variable will become null and your code which sets it won't be run. Have a look at this question for a more detailed answer.
It may be possible to work around this problem but testing all the possibilities that may cause your variable to end up null
would be time-consuming and error prone. So in my static preference classes I have made any of the methods which require a Context
take it as an argument. For example:
static int getSomeIntegerPreference(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(PREFERENCE_SOME_INTEGER, 0);
}
It's ugly but it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With