I am trying to understand the SharedPreferences of Android. I am a beginner and don't know a lot about it.
I have this class I implemented for my app Preferences
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
The thing is that I would like to set default preferences. They would be set when the app is installed and could be modified after by the application and stay persistent. I heard about a preferences.xml but I don't understand the process.
Could someone help me?
Thanks for you time
You can store default values in string resource:
and then get it as it follows:
Could you use the default value parameter of the
getX()
method?For example, to get a
String
called 'username', you could use this:You can simply define your default values in your
Preferences
class.Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:
If the variable was never accessed by the user or was never created, the system will set the default value as value and if you or the user changed this value, the default value is ignored. See http://developer.android.com/guide/topics/data/data-storage.html#pref
Directly from the Android Documentation: