0

I have a EditTextPreference and I don't know when that string get saved to the Shared Preferences file.

If I start with a null string, and change it to "Hello", when does this update get saved? Do I have to save it manually?

Joel
  • 4,732
  • 9
  • 39
  • 54
kampytime
  • 3
  • 1
  • 2

4 Answers4

2

I have a EditTextPreference and don't know when it commits that string to the Shared Preferences file

If you take a look at the EditTextPreference documentation, the text gets saved upon calling the setText(String) method. This method commits saves the text to the SharedPreferences. The preferences will never be updated until you call that method. For example...

EditTextPreference mPrefs = ...

//perform any manipulations on the string, not saved until you call setText()
String mText = "2";
mText += " + 2";
mText += " = 4";

// saves "2 + 2 = 4" to SharedPreferences
mPrefs.setText(mText);
Joel
  • 4,732
  • 9
  • 39
  • 54
1

When you commit it, by calling either Editor.commit() or Editor.apply().

See the documentation

Darwind
  • 7,284
  • 3
  • 49
  • 48
  • 2
    This is plain wrong. This applies to using `SharedPreferences.Editor`, but has nothing to do with an `EditTextPreference`. Joel's answer is correct; when you call `setText()`, it saves to `SharedPreferences`. – Geobits Jul 24 '13 at 18:42
  • You're right - sorry, I don't know how I could miss that part of the question - guess I was a bit quick to answer - give the right answer to Joel ;-) However "behind the scenes", the `Editor.commit()` is called when you call `setText(text)` ;-) – Darwind Jul 24 '13 at 19:32
  • That's true! Behind the scenes, these calls are being made. However, that is a bit beyond the scope of his question – Joel Jul 24 '13 at 19:46
  • @Joel yeah I know, that's why the credit for the correct answer should go to you ofc ;-) – Darwind Jul 24 '13 at 20:23
1

Looking at the source for EditTextPreference.java, the String is persisted in the setText() method.

So, it'll be committed to the SharedPreferences file after the text is changed.

Eric Ahn
  • 716
  • 1
  • 5
  • 15
0

when u edit your prefrence you may use the following code:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);


Editor edit = sp.edit();
edit.putString("Preference_Label", variable_name);
edit.commit(); // this commits the edit
Carbon
  • 133
  • 1
  • 4
  • 21