Home » Android » android – How to force PreferenceActivity to deal with my SharedPreferences?

android – How to force PreferenceActivity to deal with my SharedPreferences?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m using SharedPreferences to store my data across all Activities within my application. I get access to it like this:

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

I’ve implemented PreferenceActivity so users can change values through it but it happens it reads/writes data not to “MyPrefs” but to:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Which is a bit unexpected for me. Is that possible to force PreferenceActivity to deal with my “MyPrefs” preferences? And what is the point to have several preferences within single application? Thank you.

How to&Answers:

I get access to it like this

That’s fine, so long as you weren’t planning on using PreferenceActivity.

I’ve implemented PreferenceActivity so users can change values through it

Oops.

Also, get rid of getApplicationContext() there, unless you have a specific reason for using the Application rather than the activity/service/whatever. Only use the Application object when you have to and you know why you have to.

Is that possible to force PreferenceActivity to deal with my “MyPrefs” preferences?

Not readily. Unless you have some specific reason to invent your own SharedPreferences file, I’d use the default one.

And what is the point to have several preferences within single application?

You might have a reusable library or component want to store stuff in SharedPreferences, and that might have its own file so as not to mess up any preferences from the hosting application. That being said, multiple preference files is not typically needed.

Answer:

It is possible and simple. This 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);
    }
}

Answer:

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

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