Bart Friederichs
Bart Friederichs

Reputation: 33533

Using SharedPreferences and Editor as members

I have a Settings class, that uses SharedPreferences to load and save settings. To make it readable, I made the Editor and SharedPreferences objects members of that class and call on them set read and write settings. However, this doesn't seem to work well.

This is the Settings class:

public class Settings { 
    protected Context ctx;
    protected SharedPreferences sp;
    protected Editor edit;

    public Settings(Context c) {
         ctx = c;       
         sp = ctx.getSharedPreferences("app_settings", Context.MODE_PRIVATE);
         edit = sp.edit();
    }

    public void setString(String name, String value) {
        edit.clear();
        edit.putString(name, value);
        edit.commit();
    }
    public String getString(String name, String def) {
        return sp.getString(name, def);
    }
}

And I call like this (from my from Application extended MyApplication's onCreate:

Settings s = new Settings(getApplicationContext());
s.setString("foo", "bar");

When I reread that value, I always get the default value:

String value = s.getString("foo", "default");

Upvotes: 0

Views: 114

Answers (2)

Ketan Ahir
Ketan Ahir

Reputation: 6738

It is because of edit.clear()

change this method

public void setString(String name, String value) {
    edit.clear();
    edit.putString(name, value);
    edit.commit();
}

as follows

public void setString(String name, String value) {

    edit.putString(name, value);
    edit.commit();
}

Upvotes: 1

Udit Shah
Udit Shah

Reputation: 251

Try this code.

private final String LANGUAGE = "Language";//Key to identify field in sharedPrefrence file.
private final String PREFS_NAME = "SharedPreferenceFile";//Shared Preference file name.

public String getLanguageFromSharedPreference() {
    sharedPreferences = this.getSharedPreferences(PREFS_NAME, 0);
    return sharedPreferences.getString(LANGUAGE, "en");
}

public void setLanguageToSharedPreference(String newlang) {
    sharedPreferences = this.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(LANGUAGE, newlang);
    editor.commit();
}

Upvotes: 0

Related Questions