Android - Is it bad practice to have multiple Shared Preferences?

ziondreamt picture ziondreamt · Feb 18, 2014 · Viewed 8.2k times · Source

I have an app making use of SharedPreferences. One just stores app version to check against update for a changelog, the other contains some layout info that clear() gets called on as the user chooses. I finally managed to get a PreferenceFragment working and noticed a trend, so I thought I might ask this now before i go preference crazy (though I think I have enough).

I've done my best to search and see no specific mention of a problem, only that it's possible to have multiples.

I'm a little concerned about PreferenceManager.getDefaultSharedPreferences() grabbing the wrong pref, but I might simply be misunderstanding the usage.

The only relevant code i could think of from my activity:

SharedPreferences storedVer = getSharedPreferences(VER_NUM, 0);
SharedPreferences savedLayout = getSharedPreferences(LAYOUT_SAVE, 0);

Answer

tasomaniac picture tasomaniac · Feb 18, 2014

It is not bad practice at all. I think it is the opposite. I think different behaviours should use different sharedPreference files.

.getDefaultSharedPreferences() uses the default com.company.packagename.xml file. And the others create their own files.

The followings advantages of using multiple sharedPreference's come up in my mind.

  • When you use BackupManager, you can provide which sharedPreference files to backup and restore.
  • When the user logout, you can delete sharedPreference file with that users private values in it. You may not want to delete some other.