Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - storing references to ApplicationContext

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.

like image 592
nixa Avatar asked Apr 20 '10 08:04

nixa


1 Answers

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.

like image 185
Dave Webb Avatar answered Sep 27 '22 18:09

Dave Webb