开发者

SharedPreferences from multiple files

开发者 https://www.devze.com 2023-02-06 00:01 出处:网络
I have 2 files for SharedPreferences (one is displayed in a PreferenceActivity, and the second stores values which must not be seen in the PreferenceActivity). The problem - I want to load these value

I have 2 files for SharedPreferences (one is displayed in a PreferenceActivity, and the second stores values which must not be seen in the PreferenceActivity). The problem - I want to load these values from both files at startup.

  1. I tried getSharedPreferences() and passed the file name. Strangely, I can't read the real values - it always returns default values.

  2. If I am using addPreferencesFromResource() and passing the resource file ID, it reads the values, but I cant use this approach because my Activity must subclass PreferenceActivity, which I dont want to do.

How can I read values from multiple preference files? What must be passed in getSharedPreferences() as first argument (file name with extension, file name with no extension, etc.)?

There is a method PreferenceManager.getDefaultSharedPreferences(). What is "default" when I have more than 1 file?

So simple t开发者_高级运维ask to do, so much time wasted...


Short answer: it sounds like you are calling PreferenceManager.getGlobalPreferences at some point which would load the default preference file rather than your "named" preferences. If you are mixing this and context.getSharedPreferences("PREFS_NAME", Context.MODE_WORLD_READABLE) you will get weird behaviour.

Long answer: You have to specify the name of the preference file you are going to read every time you open it:

SharedPreferences prefs = context.getSharedPreferences("PREFS_NAME", Context.MODE_WORLD_READABLE)

This will force the application to make a new preference file with the filename "PREFS_NAME.xml" if it doesn't already exist and start using it.

addPreferencesFromFile() is a different function which is only used to populate the PreferenceActivity. If you don't want to use PreferenceActivity then it is useless to you.

If you DO decide to use the preference activity for your settings, use the above then set the preferences for this preference activity instance with

getPreferenceManager().setSharedPreferencesName("PREF_NAME);

Then call addPreferencesFromResource(). If you aren't using PreferenceActivity then addPreferencesFromResource() will do nothing for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消