views:

195

answers:

1

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.

+1  A: 

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.

Dave Webb
Well, I set my Preferences.applicationContext to getApplicationContent() on first activity start. So i think that it should be there unless application dies (VM dies, process gets killer, etc..). And if it dies, on next start it will initialize Preferences.applicationContext again so I think that it should work ok. I need something like that, beacuse I need access to context in some classes that don't see getApplicationContext(). For example my Category class need to download icons for each category so i set icon_path to this.filepath = Preferences.applicationContext.getCacheDir().toString
nixa
You will need to initialize `Preferences.applicationContext` in *every* Activity that uses your `Preferences` class. Your process could get killed when you're running a different Activity to your first Activity and Android can return user to that point in your application, skipping the first Activity.
Dave Webb