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");