简体   繁体   English

在sharedpreferences中设置默认值

[英]Setting a default value in sharedpreferences

Is there a method to set default values in shared preferences? 有没有一种方法可以在共享首选项中设置默认值?

Here is my load preferences code 这是我的负载偏好代码

        public void LoadPreferences() {
        SharedPreferences sharedPreferences = getSharedPreferences(values, MODE_PRIVATE);
        String strSavedMem1 = sharedPreferences.getString("MEM1", "");
        String strSavedMem3 = sharedPreferences.getString("MEM3", "");

and here is my save preferences code 这是我的保存首选项代码

        public void SavePreferences(String key, String value) {
        SharedPreferences sharedPreferences = getSharedPreferences(values, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

When you are setting preference with key and value,you are actually giving the value.So this time no question of using the default value.See, when you are retrieving the value you can define a default value if the value is not set previously. 当您使用键和值设置首选项时,实际上是在提供该值。因此,这次无需使用默认值。请参见,在检索值时,如果先前未设置该值,则可以定义一个默认值。

String strSavedMem1 = sharedPreferences.getString("MEM1", "default");

if you get strSavedMem1="default" then surely it is by default as you didn't set any other value to MEM1 in the preference 如果您得到strSavedMem1 =“ default”,那么肯定是默认情况,因为您没有在首选项中为MEM1设置任何其他值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM