Search code examples
androidandroid-preferences

setOnPreferenceChangedListener doesn't seem to function properly


In my preferences, I have a checkboxpreference and an edittextpreference. The Checkbox preference enables using a pin number to get into the application. The edittextpreference is for setting the pin. I am trying to make it so that if a user unchecks the box, it immediately erases the pin that was saved in the edit text.

CheckBoxPreference prefCodePasscode = (CheckBoxPreference) findPreference("prefCodePasscode");
        prefCodePasscode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                if (sharedPrefs.getBoolean("prefCodePasscode", false)) {
                    Toast.makeText(getApplicationContext(), "Setting Changed",
                            Toast.LENGTH_SHORT
                    ).show();
                    editor.remove("prefPasscode");
                    editor.commit();
                }
                return true;
            }
        });

What seems like it is happening is it is not actually committing the remove until the preference activity is closed. The problem this causes is if the user unchecks the box (it erases) and then rechecks it and closes the activity. It then erases the pin (however the pin is enabled.) This means when the user tries to enter a pin, there is nothing to validate it against.

Anyone have an idea why its not erasing the pin as soon as the checkbox is unchecked?

It will show the toast i have written there in the same if statement, it just wont clear the pin.

Thanks


Solution

  • Instead of removing the preference with

    editor.remove("prefPasscode");
    

    try

     editor.putString("prefPasscode", "");