bhanu kaushik
bhanu kaushik

Reputation: 391

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.

Upvotes: 1

Views: 12693

Answers (4)

IAmGroot
IAmGroot

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

EdmDroid
EdmDroid

Reputation: 1360

Enter the shared preferences in afterTextChanged()

Upvotes: 1

localhost
localhost

Reputation: 5598

  1. You should put ur method to afterTextChanged
  2. To get the result from shared preferences you should put code to onCreate method of your Activity or Fragment.

Code:

private SharedPreferences prefs.
prefs = getPreferences(Context.MODE_PRIVATE);

EditText message = (EditText)findViewById(R.id.editText);
message.setText(prefs.getString("autoSave", ""));

Upvotes: 1

Sagar Shah
Sagar Shah

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

Related Questions