我检查了SharedPreferences示例,并对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());
我想知道为什么第二到第四行:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Greeting", "Welcome to sharedpreferences!");
editor.commit();
无法重写为:
preferences.edit().putString("Greeting", "Welcome to sharedpreferences!");
preferences.edit().commit();
此更改后,LogCat不会显示任何密钥对值。用这种方式写似乎不可行。只是想知道为什么有必要声明SharedPreferences.Editor对象而不是直接从SharedPreferences类调用?
SharedPreferences的源代码:
答案 0 :(得分:0)
edit()
时,都不会被要求获得相同的编辑器,因此在commit
上调用editor
将不会提交对象preferences.edit()
中的更改,因为它可能是一个单独的对象。在你的例子中:
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
答案 1 :(得分:0)
您可以将其重写为:
SharedPreferences preferences = getSharedPreferences(name, MODE_PRIVATE);
preferences.edit()
.putString("Greeting", "Welcome to sharedpreferences!")
.commit();
Log.d("shared preferences", preferences.getAll().toString());