简体   繁体   English

默认的SharedPreferences不保存值

[英]Default SharedPreferences don't save values

I have this class: 我有这个课:

public class SharedPreferenceUtil {

private SharedPreferences prefs;

private static final String PRODUCTION_MODE_URL_GET_CHECKLIST_JSON = "www.exemplo.com/json";

//configuration keys
private static final String KEY_URL_GET_CHECKLIST_JSON = "KEY_URL_GET_CHECKLIST_JSON";

public SharedPreferenceUtil(Context context){
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
}

private void initializeDefaultAppConfigurationValues(){
    prefs.edit().putString(KEY_URL_GET_CHECKLIST_JSON, PRODUCTION_MODE_URL_GET_CHECKLIST_JSON);
    prefs.edit().commit();
}

public Configuration getConfiguration() {
    Configuration configuration = new Configuration();

    initializeDefaultAppConfigurationValues();

    configuration.setChecklistGetURL(prefs.getString(KEY_URL_GET_CHECKLIST_JSON,""));

    return configuration;
}

}

When I save the values ​​in row: prefs.edit () commit ().. It returned true. 当我将值保存在行中时:prefs.edit()commit()..它返回true。 When I try to read the value in: prefs.getString (KEY_URL_GET_CHECKLIST_JSON, ""). 当我尝试读取以下值时:prefs.getString(KEY_URL_GET_CHECKLIST_JSON,“”)。 It returned "" as if the value had not been saved. 它返回“”,好像尚未保存该值。

Could someone help me with this problem. 有人可以帮我解决这个问题。

It seems that your code is somewhat unclear 似乎您的代码不清楚

Please refer following code: 请参考以下代码:

Set: 组:

  SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
  SharedPreferences.Editor editor = settings.edit(); 
                            editor.putString("language", language);
                            editor.commit();

Read: 读:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String language = settings.getString("language", "");

please see the below link it will useful for you 请查看以下链接,它将对您有用

Sharedpreference store andr retrival 共享首选项存储ANDR检索

private SharedPreferences prefs;

you forgot about static 你忘了static

 private static SharedPreferences prefs;   

it should be ONE for all exemplars 所有示例都应该是一个

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

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