Question:
I have a class to save the email and user that connect in the application with sharedpreferences
, but it saves the data without any reference key
so when I want to save a different data without overwriting the previous one it does not do it, I imagine that I will need assign some key
to reference it and be able to save the data I want without stepping on the previous one and assigning it a name:
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
settings = PreferenceManager.getDefaultSharedPreferences(context);
editor = settings.edit();
editor.putString(PREFS_KEY, text);
editor.commit();
}
Here I call the function:
String email = _emailText.getText().toString();
sharedPreference.save(this, email);
Answer:
I don't think that the value is not being saved, the problem is that the saved value has to be obtained in this way, (assuming that your key is email
)
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String email = preferences.getString("email, "");
Remember that you use getDefaultSharedPreferences which does not require a name for the preferences file, but its preference values do.
I add how it is done with the two methods:
Save and get a value using getDefaultSharedPreferences()
public void saveValuePreference(Context context, String text) {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = PreferenceManager.getDefaultSharedPreferences(context);
editor = settings.edit();
editor.putString("email", text);
editor.commit();
}
public String getValuePreference(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString("email", "");
}
Save and get a value using getSharedPreferences()
private String PREFS_KEY = "mispreferencias";
public void saveValuePreference(Context context, String text) {
SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
SharedPreferences.Editor editor;
editor = settings.edit();
editor.putString("email", text);
editor.commit();
}
public String getValuePreference(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
return preferences.getString("email", "");
}