SharedPreferences & boolean

后端 未结 3 1877
不知归路
不知归路 2021-01-07 11:26

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?

        SharedPre         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 12:07

    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).

提交回复
热议问题