简体   繁体   English

Android更改存储的SharedPreferences值?

[英]Android change a stored SharedPreferences value?

I create a shared preferences file at login, but I cannot figure out the code to change the preferences inside of my app. 我在登录时创建了一个共享的首选项文件,但是我无法找出用于更改应用程序内的首选项的代码。

SharedPreferences.java SharedPreferences.java

    public void editHospitalId(String hospital_id) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(_context);
        Editor editor = prefs.edit();
        editor.putString(KEY_HOSPITALID, hospital_id);
        editor.commit();
}

I have already initialized a value for KEY_HOSPITALID on login: 我已经在登录时为KEY_HOSPITALID初始化了一个值:

SharedPreferences.java SharedPreferences.java

// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

// create login session

public void createLoginSession(String name, String hospital_id){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_NAME, name);

    // Storing email in pref
    editor.putString(KEY_HOSPITALID, hospital_id);

    // commit changes
    editor.commit();

I suppose I could delete the value and re-add it? 我想我可以删除该值并重新添加它? But there has to be a way to overwrite it. 但是必须有一种覆盖它的方法。

SharedPreferences contain data as key-value pairs, so calling putString(KEY, VALUE) will assign VALUE to the KEY , regardless of if it's already set. SharedPreferences包含数据作为键值对,因此调用putString(KEY, VALUE)会将VALUE赋值给KEY ,无论它是否已经设置。 In short, it deletes previous entry automatically. 简而言之,它会自动删除上一个条目。

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

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