Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force PreferenceActivity to deal with my SharedPreferences?

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.

like image 630
Eugene Avatar asked Oct 09 '11 19:10

Eugene


People also ask

How do we get access to the preference in Android?

To get access to the preferences, we have three APIs to choose from: getPreferences() : used from within your Activity, to access activity-specific preferences. getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences.

How to set and get value in SharedPreferences in Android?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

How does Shared Preferences work?

Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.


1 Answers

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);
    }
}
like image 74
xverges Avatar answered Nov 12 '22 20:11

xverges