Is it possible to have more than one SharedPreference file in Android and if so how would I go about setting it up?
I plan for the first SharedPreference to store around 7 values which will not be user based values. The second SharedPreference would contain user based values.
In this case if the user signed out from my application only the SharedPreference containing user based values would be cleared.
Yes you can do it.
For example you may do something as below to create SP
SharedPreferences prefs = getSharedPreferences("countPref", Context.MODE_PRIVATE);
If you look close countPref
is used to uniqly identify the sharedPref. So you may invoke another shared prefrence as below and use it.
SharedPreferences prefs = getSharedPreferences("countPrefTwo", Context.MODE_PRIVATE);
SharedPreferences prefs = getSharedPreferences("countPrefThree", Context.MODE_PRIVATE);
Pro tip: don't hard code the key values such as "countPref". Instead, store them on a separate class as constants and reuse them throughout the application.
Good luck!
Yes you can maintain as many shared preference files for an app as you can. Just define separate classes for each of them.
You can maintain multiple SharedPreference
files. There is nothing that I have come across that prohibits or says otherwise.
You can follow the solution here: Android Shared Preferences to help you create a helper class that will help you streamline the storage and retrieval of data from the SharedPreference
files.
EDIT: In fact, the documents: (http://developer.android.com/guide/topics/data/data-storage.html#pref) has a getSharedPreferences if you have multiple files.
So, bottom line is, yes. You can have multiple SharedPreference
files. So nothing wrong with the approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With