44

I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?

Swati Garg
  • 995
  • 1
  • 10
  • 21

3 Answers3

123

I assume by preferences you are referring to your application's preferences and not Android phone settings.

To store preferences between runs of you application you need to do the following

  1. Create a SharedPreferences object

    SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
    

    String n identifies your preferences and the second argument is the mode they'll be accessed

  2. Instantiate an Editor object

    SharedPreferences.Editor editor = settings.edit();
    

    Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work

  3. Write your preferences to the buffer

    editor.put...(String, value)
    

    There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)

  4. Flush the buffer

    editor.commit();
    

    This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.

These preferences will by stored on the phone and will only be accessible to your application.

More documentation is here

Janusz
  • 187,060
  • 113
  • 301
  • 369
Will
  • 19,789
  • 10
  • 43
  • 45
  • 45
    You can actually use one-liner: prefs.edit().putInt(key, value).commit(); – tomash Dec 30 '09 at 21:21
  • 2
    Any ideas how this differs from PreferenceActivity and do you maybe have a reference to an example of PreferenceActivity? – Eugene van der Merwe Jan 17 '11 at 19:36
  • 2
    If you don't care about the return value, the docs say that since API level 9 you can better call `apply();` instead of `commit();` – Twinone Apr 08 '13 at 16:40
  • Although I'm 5 years late here, but using what @tomash suggested failed when I wanted to create a new boolean value for my preference via java and not in the xml file. though using his line after the key was created did work. Can any one please explain what difference between Will answer and tomash? Don't they both do the same? – JustADev Aug 20 '14 at 20:58
  • @OmarBizreh - what tomash said (one liner) is exactly the same as lines 2-4 of Will's answer. (Of course you still need to create a preferences object (line 1)). I don't know what happens if you try line 1 BEFORE you've created that preference, and then are attempting to use that pref ob later -- is that what you did? If so, then the solution is: wherever in code you CREATE the preference (set the key), also set your class global that holds the pref ob. Or just be safe, and do line 1 every time... – ToolmakerSteve Sep 18 '14 at 00:07
  • @EugenevanderMerwe - PreferenceActivity or PreferenceFragment is used to display all preferences (or a group of preferences) to a user, so user can alter them. The OP is explicitly asking how he can set one or more preferences *from code*, without bringing up that GUI. So the difference is *you the programmer* setting a preference, versus *the user* setting a preference. – ToolmakerSteve Sep 18 '14 at 00:26
  • @ToolmakerSteve My preference file was already created, but I wanted to add a new key via java. So using the 1 line code didn't work. I had to use tomash code in-order to be able to add a new preference key to my already created preference file. – JustADev Sep 18 '14 at 08:44
8

I tried this but didn't work:

SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);

Try this instead:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
John Conde
  • 217,595
  • 99
  • 455
  • 496
Adan
  • 431
  • 1
  • 6
  • 9
  • It would be much more useful to say WHAT went wrong, instead of "didn't work". (It didn't compile? It crashed when you ran it? The returned list of preferences was empty?) Nevertheless, +1 for a good tip: Looking at my app, your line is what is used to access the settings from the MainActivity; the original answer's line can optionally be used to access the settings from code in a PreferenceFragment (a fragment that contains XML describing widgets for displaying/altering the preferences.) – ToolmakerSteve Sep 18 '14 at 00:18
3

You can save something in the sharedpreferences by using below code

public static void save(String valueKey, String value) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor edit = prefs.edit();
    edit.putString(valueKey, value);
    edit.commit();
    }

To read preferences:

public static String read(String valueKey, String valueDefault) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
   return prefs.getString(valueKey, valueDefault);
}