Search code examples
androidsharedpreferencesandroid-edittext

Android Save SharedPreferences from EditText


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){

    }
});
  1. I am not sure, whether to put prefs.edit().putString("autoSave", s.toString()).commit(); in onTextChanged() or in afterTextChanged.
  2. I tried to put it in both onTextChanged() and afterTextChanged but when I restart the application, there is no text that I edited.

Solution

  • 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();
      }
    
    });