Android registerOnSharedPreferenceChangeListener()

2019-01-25 14:29发布

Whenever I try to add this line it crashes my app. Am I not putting it in the right spot?

    preferences.registerOnSharedPreferenceChangeListener(myActivity.this);

Here is my class

class Simulation extends View {

    // I declare my program variables here
    public Simulation(Context context) {
        super(context);
        // get the preferences
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(context);
        preferences
                .registerOnSharedPreferenceChangeListener(myActivity.this);
        String storedPreference = preferences.getString("nPref", "0");
    }

    public void onSharedPreferenceChanged(
            SharedPreferences sharedPreferences, String key) {
        Log.i(TAG, "preferences changed!");
    }
}

Thanks!

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-25 15:15

One note about the Answer, the prefListener needs to be a class field, not a local variable or it may get garbage collected.

SharedPreferences.onSharedPreferenceChangeListener not being called consistently

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-25 15:25

Do like this

SharedPreferences.OnSharedPreferenceChangeListener prefListener = 
        new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs,
            String key) {
        if (key.equals("date")) {
        }
    }
};

and

preferences.registerOnSharedPreferenceChangeListener(prefListener);
查看更多
登录 后发表回答