Android: SharedPreferences not getting updated from PreferenceFragment

151 views Asked by At

I'm posting this question again as I didn't get any answers last time, and I still haven't solved the problem.

I have a settings menu with a PreferenceScreen in which I create a lot of CheckBoxPreferences during runtime (Adding them into the "Exclusion List" prefscreen). I created them no problem, here's the XML code below that it starts with:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceScreen
        android:key="exclusion_list_key"
        android:title="Exclusion List"
        android:persistent="true"
        android:summary="" >
    </PreferenceScreen>
</PreferenceScreen>

I create the checkboxes in the onCreate method of my PreferenceFragment and add them to the "Exclusion List" PreferenceScreen and that works fine.

I'm trying to set the summary of the "Exclusion List" to be a list of all the checkbox titles that are checked off (so if the checkbox is checked, it's name will be listed in the summary of the "Exclusion List").

In the onCreate() method, the summary gets set properly, there's no problem.

But in the onPreferenceChanged() method, I set the summary of "Exclusion List" to the 'summary' string I built (which contains the correct value), but it doesn't update it! When i press back from my checkbox menu, the "Exclusion List" does not have the updated values.

The last few lines are the ones of interest. I did some printlns to see what's going on:

  1. The listener works fine, runs when expected

  2. My summary var contains what's expected

  3. After calling setSummary(summary), the getSummary() returns the expected value (so that means it got set properly)

  4. However, when I actually press back and see "Exclusion List", it's summary doesn't actually get updated!

Did I miss something? Thanks in advance!

All the code for reference:

public class Settings extends AppCompatActivity {

    public static final String EXC_LIST_KEY = "exclusion_list_key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);
            String summary = "";

            //Create all the checkboxes inside of the PreferenceScreen
            for (int i = 0; i < MainActivity.contactNames.length; i++) {
                CheckBoxPreference checkbox = new CheckBoxPreference(getActivity());
                checkbox.setTitle(MainActivity.contactNames[i][0]);
                checkbox.setKey(MainActivity.contactNames[i][2]);
                checkbox.setSummary(MainActivity.contactNames[i][1]);
                checkbox.setDefaultValue(false);
                ((PreferenceScreen) findPreference(EXC_LIST_KEY)).addPreference(checkbox);
                if (checkbox.isChecked()) {
                    summary = summary + checkbox.getTitle() + "\n";
                }
            }
            findPreference(EXC_LIST_KEY).setSummary(summary);
            getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            //Checkbox keys all start with 'key_'
            if (key.startsWith("key_")) {
                String summary = "";
                for (int i = 0; i < MainActivity.contactNames.length; i++) {
                    CheckBoxPreference checkbox = (CheckBoxPreference) findPreference(MainActivity.contactNames[i][2]);
                    if (checkbox.isChecked()) {
                        summary = summary + checkbox.getTitle() + "\n";
                    }
                }
                System.out.println("Summary I have: " + summary); //Correct summary is printed out
                findPreference(EXC_LIST_KEY).setSummary(summary); //Isn't updating the value???
                System.out.println("Summary system has: " + findPreference(EXC_LIST_KEY).getSummary()); //Correct summary is printed out
            }
        }
    }
}
2

There are 2 answers

0
user1429039 On BEST ANSWER

Got it working by adding the following line of code to the end of my onSharedPreferenceChanged() method:

((BaseAdapter)getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
0
rafsanahmad007 On

try Adding this code in your SettingsFragment

 @Override
public void onResume() {
    super.onResume();

    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();

    // CHANGE 1: load saved values to set the summaries
    onSharedPreferenceChanged(prefs, "exclusion_list_key");

    // CHANGE 2: register shared prefs listener in onResume
    prefs.registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
    prefs.unregisterOnSharedPreferenceChangeListener(this);
}