How to get PreferenceActivity to work with my SharedPreferences?

I use SharedPreferences to store my data in all Activities in my application. I access it as follows:

 SharedPreferences mSharedPreferences = getSharedPreferences("MyPrefs", 0); 

I implemented PreferenceActivity so that users can change values ​​through it, but this happens when reading / writing data not in "MyPrefs", but in:

 PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 

Which is a little unexpected for me. Is it possible to get PreferenceActivity use my "MyPrefs" settings? And what's the point of having multiple preferences in one application? Thanks.

+7
source share
3 answers

I access it like this

This is great if you do not plan to use PreferenceActivity .

I implemented PreferenceActivity so that users can change values ​​through it

Unfortunately.

Also get rid of getApplicationContext() there if you have no specific reason to use Application , and not an action / service / something else. Use only the Application object when you need it and you know why you need it.

Is it possible to get PreferenceActivity to work with my MyPrefs settings?

Not easy. Unless you have a specific reason to come up with your own SharedPreferences file, I would use it by default.

And what's the point of having multiple preferences in one application?

You may have a library or reusable component that wants to store things in SharedPreferences , and this may have its own file so as not to spoil any hosting preferences. This usually does not require multiple preference files.

0
source

It is possible and simple. It worked for me

 public class SettingsActivity extends PreferenceActivity { @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName("MyPrefs"); //getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_WRITEABLE); addPreferencesFromResource(R.xml.preferences); } } 
+14
source

I would recommend just using PreferenceManager.getDefaultSharedPreferences (context) everywhere, which is the same as using preference activity. But if you need to stick with your current setup, then the hacky solution (but the only thing I know) is to override getSharedPreferences to return what you want.

 @Override public SharedPreferences getSharedPreferences(String name, int mode) { return super.getSharedPreferences("MyPrefs", mode); } 
+4
source

All Articles