LoginSignup
5
2

More than 5 years have passed since last update.

SharedPreferencesの反映はapplyを使おう

Posted at

SharedPreferencesへの書き込みの反映には下記2点のメソッドが用意されています。

業務で以下のようなコードでcommitの方が使われており、PlayConsoleにANRのレポートが上がってきました。
commitはドキュメントにもあるように同期的にファイルへ書き出しを行っているため、書き出しに時間がかかりレポートされたと考えられます。

fun save(context: Context, value: Int) {
    val pref = context.getSharedPreferences("PREF", Context.MODE_PRIVATE)
    val editor = pref.edit()
    editor.putInt("KEY", value)
    editor.commit()
}

そこで、非同期で書き込みを行うapplyに置き換え対応しました。

fun save(context: Context, value: Int) {
    val pref = context.getSharedPreferences("PREF", Context.MODE_PRIVATE)
    val editor = pref.edit()
    editor.putInt("KEY", value)
    editor.apply()
}
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2