Why using SharedPreferences.Editor object to modify data rather than SharedPreferencesInstace.edit()?
I check the SharedPreferences example and curious about the code for data modification in SharedPreferences:
SharedPreferences preferences = getSharedPreferences (name, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit()开发者_Python百科;
editor.putString("Greeting", "Welcome to sharedpreferences!");
editor.commit();
Log.d("shared preferences", preferences.getAll().toString());
I wonder why the lines of second to fourth:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Greeting", "Welcome to sharedpreferences!");
editor.commit();
can't rewrite as:
preferences.edit().putString("Greeting", "Welcome to sharedpreferences!");
preferences.edit().commit();
LogCat does not show up any key pair values after this change. It seems not feasible to write with this way. Just wonder why it necessary to declare an SharedPreferences.Editor object rather than directly called from the SharedPreferences class?
The source code of SharedPreferences:
http://www.java2s.com/Open-Source/Android/UnTagged/dexandroid/android/content/SharedPreferences.java.htm
- The link you gave is for documentation and interface, not the actual implementation of the SharedPreferences you got.
- You are not promised to get the same editor each time you call
edit()
, so callingcommit
oneditor
will not commit the changes in the objectpreferences.edit()
since it might be a separate object.
In your example:
SharedPreferences.Editor editor = preferences.edit();
// ^object #1
editor.putString("Greeting", "Welcome to sharedpreferences!");
//^object #1
editor.commit();
//^object #1
preferences.edit().putString("Greeting", "Welcome to sharedpreferences!");
// ^object #2
editor.commit();
//^object #1
You can rewrite it as:
SharedPreferences preferences = getSharedPreferences(name, MODE_PRIVATE);
preferences.edit()
.putString("Greeting", "Welcome to sharedpreferences!")
.commit();
Log.d("shared preferences", preferences.getAll().toString());
精彩评论