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 SharedPreferences. For instance many people say the appropriate way to access it is via this call:
PreferenceManager.getDefaultSharedPreferences(Context context)
However it seems like this could be dangerous. If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well. It seems to me that the better call to use would be:
Context.getSharedPreferences(String name, int mode)
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class. You could use the fully qualified name of the class to ensure that the file will most likely not be duplicated by someone else.
Also based on this SO question: Should accessing SharedPreferences be done off the UI Thread?, it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
Libraries should not use that particular
SharedPreferences. The defaultSharedPreferencesshould only be used by the application.You are certainly welcome to do this. I wouldn’t, at the application level, as the primary reason for
SharedPreferencesis to have them be shared among the components in the application. A development team should have no problem managing this namespace, just as they should have no problem managing names of classes, packages, resources, or other project-level stuff. Moreover, the defaultSharedPreferencesare what yourPreferenceActivitywill use.However, going back to your libraries point, reusable libraries should use a separate
SharedPreferencesfor their library only. I would not base it on a class name, because then you are one refactoring away from breaking your app. Instead, pick a name that is unique (e.g., based on the library name, such as"com.commonsware.cwac.wakeful.WakefulIntentService") but stable.Ideally, yes. I recently released a
SharedPreferencesLoaderthat helps with this.Don’t over-rely upon them. They are stored in XML files and are not transactional. A database should be your primary data store, particularly for data you really don’t want to lose.