'SharedPreferences.Editor vs onSharedPreferenceChanged listener

I have an activity that implements SharedPreferences.OnSharedPreferenceChangeListener

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_visualizer);
    mVisualizerView = (VisualizerView) findViewById(R.id.activity_visualizer);
    setupSharedPreferences();
    setupPermissions();
}

private void setupSharedPreferences() {




    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mVisualizerView.setShowBass(sharedPreferences.getBoolean(getString(R.string.pref_show_bass_key), getResources().getBoolean(R.bool.pref_show_bass_default)));

    mVisualizerView.setShowMid(true);
    mVisualizerView.setShowTreble(true);
    mVisualizerView.setMinSizeScale(1);
    mVisualizerView.setColor(getString(R.string.pref_color_red_value));

    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}

I have an override method that listens to a preference change

    @Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if(key.equals(getString(R.string.pref_show_bass_key))){
        mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));
    }

}

I wonder what mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default))); inside the override method does because what I know is that if we want to put values inside preference object is that we should use SharedPreferences.Editor just like

    editor.putBoolean(key, value);

setShowBass is a setter method for the mVisualizerView not the method used for storing values that we want to save

if we want to retrieve the data we use

    sharedPreferences.getBoolean(key, value);

why my code works without using the editor object for storing and retrieving of data?



Solution 1:[1]

Yes everything you assuming is correct, and the code you shared is also correct.

mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));

This code is retrieving a boolean from sharedPreferences WHICH MIGHT BE SETTING IN from some change visualiser settings screen.

onSharedPreferenceChanged

is just an observer which is listening if any of visualiser/player setting is changed then update the view accordingly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Irfan Anwar