7

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.

Mark O'Sullivan
  • 10,138
  • 6
  • 39
  • 60
Dinesh T A
  • 2,087
  • 4
  • 26
  • 34

3 Answers3

9

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!

Jay Mayu
  • 17,023
  • 32
  • 114
  • 148
4

Yes you can maintain as many shared preference files for an app as you can. Just define separate classes for each of them.

Ameer Moaaviah
  • 1,530
  • 12
  • 27
1

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.

Community
  • 1
  • 1
Siddharth Lele
  • 27,623
  • 15
  • 98
  • 151