2017-10-04 188 views
-3

我更改了共享首选项值,但仍返回旧值。我错过了什么?SharedPreferences即使在编辑后也会返回相同的值

此代码在用户单击RecyclerView中的项目时执行。因此,在第一次点击时,我收到了预期的消息" this true"。但第二次点击我也得到" this true",但预计"this false"

SharedPreferences prefs = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE); 
    boolean value = prefs.getBoolean(KEY_PREF, true); 
    if (value) { 
     Log.v(LOG_TAG, "this true"); 
     Log.v(LOG_TAG, "editing value.."); 
     SharedPreferences.Editor prefs = context.getSharedPreferences(MY_PREF, MODE_PRIVATE).edit(); 
     prefs.putBoolean(KEY_PREF, new_value); 
     prefs.apply(); 
    } else { 
     Log.v(LOG_TAG, "this false"); 
    } 
+0

'new_value'的值是什么?也许你应该保存'!value'。这将切换值。 –

回答

0

呼叫prefs.apply是异步的。你可能看不到即时的变化。相反,您可以使用同步的prefs.commit

3

所有你存储的是true,总是,所以没有办法显示this false,因为它永远不会发生。实际上,您的代码将不会编译,因为new_value从未声明未分配。

PS:没有意义第二次拨打getSharedPreferences()。在输入if()区块之前,您已经在prefs中得到了它。

+0

是的,对不起。其实我把newValue那里 –

+0

更新问题 –

+0

这只是一段代码。我已经宣布并分配了 –

相关问题