Search code examples
javaandroidandroid-studioandroid-preferences

On Preference change listener - after click run twice


I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...

Here is the code:

SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.admin_activity);

myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            switch(key) {
                case "prefAddUser":
                    EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
                    String jmeno = connectionPref.getText();
                    System.out.println("now");
                    add_user(jmeno); //custom method to add user to MySQL database
                    Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
                    connectionPref.setText("");
                    break;

            }
        }
    };
}
@Override
protected void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}



@Override
protected void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);

}

I don't know what to do with this weird problem... What should I do?


Solution

  • Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
    As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.


    Implement it in the class scope like this:

    public class SettingsActivity extends PreferenceActivity
                                  implements OnSharedPreferenceChangeListener {
        public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
        ...
    
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
            if (key.equals(KEY_PREF_SYNC_CONN)) {
                Preference connectionPref = findPreference(key);
                // Set summary to be the user-description for the selected value
                connectionPref.setSummary(sharedPreferences.getString(key, ""));
            }
        }
    }
    


    Read the next tutorials for further explanation:
    1. Good So answer on the subject
    2. Official documentation here