Android SharedPreferences Best Practices

前端 未结 5 1083
醉梦人生
醉梦人生 2020-12-22 19:38

In an application I have been building we rely on SharedPreferences quite a bit, this got me thinking about what is best practice when it comes to accessing SharedPreference

5条回答
  •  既然无缘
    2020-12-22 20:21

    Let's assume in a project, with multiple developers working on it, they are defining SharedPreference within an Activity like this:

    SharedPreferences sharedPref = context.getSharedPreferences("prefName", 0);
    

    At one point or another two developers can define the SharedPreference with the same name or insert equivalent Key - Value pairs, which will lead to problems in using the keys.

    The solution relies on two options, whether to use;

    1. SharedPreferences Singleton that uses String keys.

    2. SharedPreferences Singleton that uses Enum keys.

    Personally and According to this Sharepreference Documentation, I prefer to use Enum keys as it enforces stricter control when there are multiple programmers working on a project. A programmer has no choice but to declare a new key in the appropriate enum class and so all the keys are in the same place.

    And to avoid boilerplate code writing create the SharedPreference singleton. This SharedPreferences singleton Class help to centralize and simplify reading and writing of SharedPreferences in your Android app.

    The source code for the two provided solutions can be found in GitHub

提交回复
热议问题