简体   繁体   中英

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

    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:

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. In short, it deletes previous entry automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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