SharedPreferences & boolean

最后都变了- 提交于 2019-12-19 04:38:29

问题


I'm trying to set the "isPhysicalTheftEnabled" to false when a method is executed, but this doesn't seem to work. Anyone have any idea?

        SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("isPhysicalTheftEnabled", false);

回答1:


Try adding ed.commit().

i.e.:

SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("isPhysicalTheftEnabled", false);
ed.commit();

SharedPreferences.Editors require that you commit anything you change in your SharedPreferences for the changes to apply.

Regarding your comment on Ankit's answer:

To set the checked property of your CheckBox based on the value of the boolean you saved to SharedPreferences, you need something like:

SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
myCheckBox.setChecked(sp.getBoolean("isPhysicsTheftEnabled", [true/false]);

.. in which you pick either true or false for the def_value of .getBoolean() (if the SharedPreferences can't find the boolean).




回答2:


You need to call ed.apply() after changing values in SharedPreferences.

You can also use ed.commit() if you want to check for errors. commit() (unlike apply()) returns false if the data was not (correctly) written to the persistent storage.




回答3:


You need to call editorObject.commit(); after you done with putting data into SP.

For your problem replace your code with below code...

        SharedPreferences sp = getSharedPreferences("isPhysicalTheftEnabled", MODE_WORLD_READABLE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean("isPhysicalTheftEnabled", false);
        ed.commit();


来源:https://stackoverflow.com/questions/11671141/sharedpreferences-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!