0

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 :).

user1567896
  • 2,398
  • 2
  • 26
  • 43

2 Answers2

2

simple:

SharedPreferences prefs = context.getSharedPrefernces("fileName", 0);
Budius
  • 39,391
  • 16
  • 102
  • 144
  • Thanks, sometimes it is so easy ;). But how do I bind non default preferences to my preferences.xml, so that the values get updated automatically? – user1567896 Jan 24 '14 at 09:49
  • You have to do it like i wrote first. Have a look here: http://stackoverflow.com/a/6822461/1965084 I didn't understand the downvote without comment anyway... – alex Jan 24 '14 at 09:54
  • @alex: I don't want to write to the preferences manually. I'd like to bind a none default preference file to my preferences, so that they get updated automatically if the user changes any values. The background is that I'm coding a widget. Any widget should have its own persistent preferences. By the way I did not downvote you. But I'll give you an upvote. – user1567896 Jan 24 '14 at 10:01
  • thanks :) have a look at the link, it explains how to bind your properties to a preferences xml automatically in a not deprecated way. – alex Jan 24 '14 at 10:32
0

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.

alex
  • 5,516
  • 2
  • 36
  • 60