Reputation: 391
In my application, I have an EditText
for the user to enter a text. So, I want to save the text of an EditText
in SharedPreferences
. I want the SharedPreferences
to be updated when the text from editText is changed.
I am using this code:
message = (EditText) findViewById(R.id.et_message);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
message.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count){
prefs.edit().putString("autoSave", s.toString()).commit();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
@Override
public void afterTextChanged(Editable s){
}
});
prefs.edit().putString("autoSave",
s.toString()).commit();
in onTextChanged()
or in afterTextChanged.onTextChanged()
and afterTextChanged but when I restart the application, there is no text that I edited. Upvotes: 1
Views: 12693
Reputation: 13855
You are saving the text fine, but you never load it when you load your application.
Try adding this line to set the text:
message.setText(prefs.getString("autoSave", ""));
See full example below
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
message.setText(prefs.getString("autoSave", ""));
message.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count){
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
@Override
public void afterTextChanged(Editable s){
prefs.edit().putString("autoSave", s.toString()).commit();
}
});
Upvotes: 14
Reputation: 5598
afterTextChanged
Code:
private SharedPreferences prefs.
prefs = getPreferences(Context.MODE_PRIVATE);
EditText message = (EditText)findViewById(R.id.editText);
message.setText(prefs.getString("autoSave", ""));
Upvotes: 1
Reputation: 4292
Have a look at Well formated Shared Preference example here.
What you have to do is In your onCreate() method: Just put this:
message.setText(prefs.getString("autoSave", null));
Upvotes: 1