Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having more than one Shared Preference file in Android [duplicate]

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.

like image 717
Dinesh T A Avatar asked Mar 29 '13 06:03

Dinesh T A


3 Answers

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!

like image 182
Jay Mayu Avatar answered Sep 28 '22 02:09

Jay Mayu


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

like image 20
Ameer Moaaviah Avatar answered Sep 28 '22 02:09

Ameer Moaaviah


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.

like image 34
Siddharth Lele Avatar answered Sep 28 '22 04:09

Siddharth Lele