在sharedpreferences中设置默认值

在sharedpreferences中设置默认值

本文介绍了在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");

如果你得到strSavedMem1 =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

这篇关于在sharedpreferences中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:41