这是内容的翻译: 离开SharedPreferences和Editor打开是否有问题

huangapple go评论75阅读模式
英文:

Is it bad leaving SharedPreferences & Editor open

问题

例如,你有这个类

private SharedPreferences sp
private SharedPreferences.Editor editor

protected void onCreate(..) {
this.sp = ...
this.editor = this.sp.edit();
}

这样做有问题吗?

英文:

e.g. you have this class

private SharedPreferences sp
private SharedPreferences.Editor editor

protected void onCreate(..) {
this.sp = ...
this.editor = this.sp.edit();
}

Is it bad to do that?

答案1

得分: 0

共享偏好设置是正常的,但编辑器不行。
只要您不调用编辑器的 commit 或 apply 方法,值就不会被写入 preferences.file,我认为在从 sp 中读取时也不会获取到这些值。

所以作为一种习惯,写入偏好设置值时始终这样做(Java)

sp.edit().putString(key, value).apply()

或者使用 putInt、putBoolean 等方法。

英文:

The shared preferences are ok, the editor isn't.
As long as you do not call editor's commit or apply, the values are not written to the preferences.file and I think you also will not get the values when reading from sp.

So as a habit, always do this when writing a preference value (Java)

sp.edit().putString(key, value).apply()

Or putInt, putBoolean etc.

huangapple
  • 本文由 发表于 2020年4月7日 11:10:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61072214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定