java - SharedPreferences apply() 保存上述所有内容还是仅保存最后一个?怎么运行的?

标签 java android sharedpreferences android-preferences preferences

我的问题很简单,但我没有找到答案(很抱歉,如果它在某个地方但没有找到)。

sharedpreferences.editor.apply()如何工作?

为了清楚起见,我有以下代码:

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

这适用于我的项目。但是就性能而言,使用上面的还是下面的更好?

MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();

基本上,上面的代码是正确的吗?
它适用于上面的所有 putSomething 还是 apply() 仅适用于一个 putSomething

最佳答案

应用与提交

使用 apply() 和 commit() 的主要区别

.apply() 将在后台线程中保存您的更改。

.commit() 将在主线程中保存您的更改。

这两种方法会产生相同的结果。

关于java - SharedPreferences apply() 保存上述所有内容还是仅保存最后一个?怎么运行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731854/

相关文章:

java - 如何使用 Sharedpreference 存储一个 int?

java - Android:在扩展 View 的类中的 startActivity()

说明 amazon dynamodb 用法的 java 代码示例

c# - Android 中的 JSON 数组错误

java - 我可以使用 JSONArray 而不是创建数据模型吗?

Android libc.so 崩溃?

android - 更改 ScrollView 指示器的颜色

android - 用户可以编辑他们在手机上使用的应用程序的 SharedPreferences

android - 显示当前歌曲名称

java - 如何从字符串中删除所有非字母数字字符而不删除@符号