Search code examples
android-fragmentsandroid-preferences

Can't retrieve android preferences from preference.xml


I have been looking at preferences in android, but I think I must be getting something wrong. My basic idea is to have a preference.xml file (located in res/xml), which stores a bunch of data, including ListPreference etc. I have set default values in the XML, but when I try to retrieve the values in a separate fragment, it can't seem to find the preference.

Code of the function in my Fragment:

public static void attemptToAddToCalendar(final Context context, final SessionEntity session){

        SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        Toast.makeText(context, "preferences are" + sharedPreferences.getString("pref_addToCalendarAutomatically-list", "Unknown"), Toast.LENGTH_LONG).show();

Code of the preferences.xml;

<ListPreference
            android:key="pref_addToCalendarAutomatically-list"
            android:entries="@array/pref_ARaddToCalendarAutomatically"
            android:entryValues="@array/pref_ARaddToCalendarAutmaticallyValues"
            android:defaultValue="2"
            android:summary="Add favorites to calendar"
            android:title="Calendar Options" ></ListPreference>
</PreferenceCategory>

The array Now this will only output the text "preferences are Unknown", which evidently means it can't find the values. But I don't understand why.


Solution

  • Thank you for the comment! It was indeed only the layout. In hindsight it's kind of obvious, but I was kind of blind...

    For anyone that stumbles across the same thing, I modified my code as follows:

    Fragment function:

      public static void attemptToAddToCalendar(final Context context, final SessionEntity session){
    
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            Toast.makeText(context, "preferences are " + sharedPreferences.getString("prefAddToCalendarAutomaticallylist", "Unknown"), Toast.LENGTH_LONG).show();
    

    And the XML accordingly:

    <ListPreference
            android:key="prefAddToCalendarAutomaticallyList"
            android:entries="@array/prefARaddToCalendarAutomatically"
            android:entryValues="@array/prefARaddToCalendarAutomaticallyValues"
            android:defaultValue="2"
            android:summary="Add favorites to calendar"
            android:title="Calendar Options" >
    </ListPreference>
    

    This was driving me nuts, so thanks again!