Search code examples
androidsharedpreferencesandroid-preferences

does the context passed on getDefaultSharedPreferences affects the result?


I'm getting an weird error so I'm trying to eliminate the possibilities.

Does the context passed to PreferenceManager.getDefaultSharedPreferences() changes the result?

I mean, when i'm writting setting to my app i never pay attention which context i pass to this method since it is a valid context...

Sometimes i put the Activity, sometimes the Appliaction whatever context i've on hands

Is it wrong? I've noticed that i'm getting wrong preferences values at some point, and i dont know if there is a bug in my code or if this be


Solution

  • It doesn't matter whether you provide an Application or an Activity as the Context parameter for PreferenceManager.getDefaultSharedPreferences().

    If you look at the source for getDefaultSharedPreferences():

    return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
            getDefaultSharedPreferencesMode());
    

    Looking further, into getDefaultSharedPreferencesName(context):

    return context.getPackageName() + "_preferences";
    

    This means that for any Context of your application, you'll get the same SharedPreferences back, as your application ID does not change based on Activity or Application.

    The only time you could run into a potential issue is if you are manually creating a Context for another package (e.g. using Context.createPackageContext()).