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.
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.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With