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.
I have a static Preferences class that hold some application preferences and stuff like
Share
You’re right to use the
ApplicationContextthere since if you don’t it can cause significant memory leaks.However, the problem you have is that the
staticvariable 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 yourstaticvariable 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
nullwould be time-consuming and error prone. So in my static preference classes I have made any of the methods which require aContexttake it as an argument. For example:It’s ugly but it works.