gobernador
gobernador

Reputation: 5739

SharedPreferences vs. Private File

In my app, I use a PreferenceActivity framework to store persistent data. My intent is to create multiple save files, all of which may be accessed by the Preferences, but only one at a time.

When is it better to use a private file generated by Context.openFileOutput() and when is it better to use SharedPreferences?

EDIT
My data exists solely in primitives.

Upvotes: 3

Views: 1210

Answers (1)

louielouie
louielouie

Reputation: 14941

Normally developers use a preference file that is common to an entire app using getDefaultSharedPreferences.

However, Android has a getSharedPreferences(String name, int mode) method in Context. You could use this to have multiple preference files, in your case - save files, by using unique names passed into the name parameter.

Regarding volatility, you can force the preferences to save by getting an Editor via edit() and then calling commit().

Make sure to note that the SharedPreferences will indeed be shared based on the name:

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

Upvotes: 1

Related Questions