Search code examples
androidandroid-toastpreferencescreenandroid-sharedpreferencescheckboxpreference

Why Toast appears more times than I need?


The problem is that a Toast appears as many times as you open Settings activity, while I need it only once after each click on CheckBox.

Thanks in advance to everyone, who tried to improve my code.

More detailed description of how the code works:

  • I go to Settings activity and check a box
  • Toast appears once
  • I return to previous activity using Back button, do nothing, return to Settings activity once more and check a box.
  • Toast appears twice
  • I return to previous activity using Back button, do nothing, return to Settings activity once more and check a box.
  • Toast appears three times
  • And so on

    public class PrefActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_screen);
        Context context = getApplicationContext();
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        settings.registerOnSharedPreferenceChangeListener(this);
    }
    
    public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
        Toast mToast;
        mToast = Toast.makeText(this, "toast text", Toast.LENGTH_SHORT);
        if(key.equals("checkbox_key")){
            mToast.show();
        }
    }
    

    }


Solution

  • You should call settings.unregisterOnSharedPreferenceChangeListener() in your onPause() method when you leave the Activity. And I suggest to call settings.registerOnSharedPreferenceChangeListener() in your onResume() callback rather than onCreate().