simple:
SharedPreferences prefs = context.getSharedPrefernces("fileName", 0);
Question
how can I write and read preferences to and from an non default file using androids preferences.
Following code is working but it is deprecated:
public class MyPreferencesActivity extends PreferenceActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName("my_preferences");
prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.preferences);
}
}
In addition I need to bind the custom preference file to my Activitiy/Fragment so that any user changes in the preferences by the user are saved automatically to the custom file.
The background is following: I'm writing a widget and every instance of that widget needs its own preferences. So I need to save and load the preference for every widget seperatly.
I did not find any solution for this without using deprecated code. Any help is really welcome :).
Solution
simple:
SharedPreferences prefs = context.getSharedPrefernces("fileName", 0);
OTHER TIPS
To read and write settings on your own you can use the following code:
// Get preferences
SharedPreferences sharedPreferences = PreferenceManager.setSharedPreferencesName("SomeFilename",0);
PreferenceManager.setSharedPreferencesMode(MODE_WORLD_READABLE);
// Read some values
String name = sharedPreferences.getString("Key", "defaultValue");
[...]
//Write preferences
SharedPreferences sharedPreferences = PreferenceManager.getSharedPreferencesName("SomeFilename", 0);
// Write some values
Editor editor = sharedPreferences.edit();
editor.putString("key", "someValue");
[...]
editor.commit();
Documentation can be found here.