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();
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:
edit(), so callingcommitoneditorwill not commit the changes in the objectpreferences.edit()since it might be a separate object.In your example: