44

As the title says, I want to save and retrieve certain strings. But my code won't pass through the first line neither in retrieve or store. I tried to follow this link: http://developer.android.com/guide/topics/data/data-storage.html

private void savepath(String pathtilsave, int i) {
    String tal = null;
    // doesn't go past the line below
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    tal = String.valueOf(i);
    editor.putString(tal, pathtilsave);
    editor.commit();
}

and my retrieve method:

public void getpaths() {
    String tal = null;
    // doesn't go past the line below
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    for (int i = 1; i <= lydliste.length - 1; i++) {
        tal = String.valueOf(i);
        String restoredText = settings.getString(tal, null);
        if (restoredText != null) {
            lydliste[i] = restoredText;
        }
    }
}

lydliste is a static string array. PREFS_NAME is

public static final String PREFS_NAME = "MyPrefsFile";
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Rad
  • 830
  • 1
  • 12
  • 24
  • Look at this . http://stackoverflow.com/a/11894634/614807 – Chirag Aug 22 '12 at 13:26
  • There is a nice [library](https://github.com/frankiesardo/icepick) which saves you some boilercode, if you only store and restore the values in one particular activity – Templum Feb 13 '16 at 12:48
  • Use apply() instead; commit() is synchronous, whereas apply() is asynchronous. apply() will handle in the background. – Vaibhav Oct 04 '19 at 04:39

7 Answers7

89

To save to preferences:

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL", "myStringToSave").apply();  

To get a stored preference:

PreferenceManager.getDefaultSharedPreferences(context).getString("MYLABEL", "defaultStringIfNothingFound"); 

Where context is your Context.


If you are getting multiple values, it may be more efficient to reuse the same instance.

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
 String myStrValue = prefs.getString("MYSTRLABEL", "defaultStringIfNothingFound");
 Boolean myBoolValue = prefs.getBoolean("MYBOOLLABEL", false);
 int myIntValue = prefs.getInt("MYINTLABEL", 1);

And if you are saving multiple values:

Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();
prefEditor.putString("MYSTRLABEL", "myStringToSave");
prefEditor.putBoolean("MYBOOLLABEL", true);
prefEditor.putInt("MYINTLABEL", 99);
prefEditor.apply();  

Note: Saving with apply() is better than using commit(). The only time you need commit() is if you require the return value, which is very rare.

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • 1
    @dinosaur You Can probably just replace `context` with `getBaseContext()` or similar methods if within an activity. If your within some object class, You probably initialised it with `content` parameter, in which you can declare it as a global varialble on creation and use it here. – IAmGroot Aug 22 '12 at 13:36
  • Hmm. There's apparently something I'm just not getting. I've tried to write: PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString(tal, pathtilsave).commit(); and I've tried to change my method to: private void savepath(Context context, String pathtilsave, int i) with context being "this" as parameter. Still doesn't work. Doing it wrong? – Rad Aug 22 '12 at 13:40
  • @dinosaur How far does it get? Are you sure this `pathtilsave` isnt null? Try hardcoding the variables like in my example, and see if it works. If it does, it must be your parameters. – IAmGroot Aug 22 '12 at 13:47
  • http://img1.uploadscreenshot.com/images/main/8/23400324057.jpg If I debug further it'll crash and write: http://img1.uploadscreenshot.com/images/main/8/23400333032.jpg I'm pretty new at this, so sorry if I'm missing something essential. – Rad Aug 22 '12 at 13:52
  • @dinosaur Thats not a crash. Thats it trying to show you code that it doesnt have stored (doesnt have source code, just compiled android code). Because you are in debug mode stepping through and into code android code. Just keep hitting the step through button, or continue to next breakpoint. (PRESS F8 to continue through debug mode, of F6 to conitnue stepping. WIth F7 to step out of android code if you get into it.) – IAmGroot Aug 22 '12 at 13:56
  • No matter what kind of "step" I use, the same message pops up for some reason. But since that's the only line in my "save/store", it doesn't have anywhere else to jump to? does it? When I run it (instead of debug) it just goes black screen and then writes "application has stopped". – Rad Aug 22 '12 at 14:04
  • @dinosaur It has the option of going to end of method. If you get into android code hit F7 to come back out. Or F8 to continue running. Anyway: Post your logcat when it hits "application has stopped" in run mode. And what line it stopped on, if you know. – IAmGroot Aug 22 '12 at 14:05
  • http://img1.uploadscreenshot.com/images/main/8/23400511327.jpg Right about here. – Rad Aug 22 '12 at 14:10
  • @dinosaur Where is your context coming from? It seems your context is null? Try checking this in debug mode by inspecting it. – IAmGroot Aug 22 '12 at 14:20
  • http://img1.uploadscreenshot.com/images/orig/8/23401043134-orig.jpg The first picture is how the method is called. It doesn't seem null. – Rad Aug 22 '12 at 14:23
  • Last thing I can think of is to try `savepath(getBaseContext(), test.toString(), number);`. Im pretty sure there is something wrong with the context, and Ive had it play up on me before, but getBaseContext() fixed it. – IAmGroot Aug 22 '12 at 14:29
  • 2
    Nope. Same thing happened again. It's alright. Gonna try some of the other suggestions and see if that works. Your help was really appreciated. – Rad Aug 22 '12 at 14:33
10
private static final String PREFS_NAME = "preferenceName";

public static boolean setPreference(Context context, String key, String value) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);
    return editor.commit();
}

public static String getPreference(Context context, String key) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    return settings.getString(key, "defaultValue");
}
Benito Bertoli
  • 25,285
  • 12
  • 54
  • 61
  • `SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0); settings = c.getSharedPreferences(PREFS_NAME, 0);` Isn't the second line redundant? BTW , I edited it now – eRaisedToX Apr 30 '17 at 06:21
  • @eRaisedToX you're absolutely correct. Your edit was somehow rejected, so I went ahead and edited the answer myself, and made some more improvements. – Benito Bertoli May 02 '17 at 08:15
5

I solved it! It didn't work when I called the methods from within the class! I had to call it from another class for some reason, and write "classname.this" as Context parameter. Here's the final working:

SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    settings = ctx.getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(tal, pathtilsave);
     editor.commit(); 
Rad
  • 830
  • 1
  • 12
  • 24
4

Simple steps to save a String with SharedPreferences:

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);

    prefs.edit().putString("userName", "NEC").apply();

    String name = prefs.getString("userName", "");

    Log.i("saved string", name);
}
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Nech
  • 148
  • 5
3

try it with context:

final SharedPreferences settings = context.getSharedPreferences(
            PREFS_NAME, 0);

return settings.getString(key, null);
nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • this seem to work for the retrieve-part, but it's kinda hard to know for sure since i haven't stored anything. still having trouble with storing-part. thanks for this though! – Rad Aug 22 '12 at 15:41
3

If you do not care about the return value of commit() better use apply() as it being asynchronous is faster that commit().

final SharedPreferences prefs =  context.getSharedPreferences("PREFERENCE_NAME",
                Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();

As per docs

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

The SharedPreferences class allows you to save preferences specific to an android Application.

API version 11 introduced methods putStringSet and getStringSet which allows the developer to store a list of string values and retrieve a list of string values, respectively.

An example of storing an array of strings using SharedPreferences can be done like so:

// Get the current list.

SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());

// Add the new value.

myStrings.add("Another string");


// Save the list.
 editor.putStringSet("myStrings", myStrings); editor.commit();
NightFury
  • 13,436
  • 6
  • 71
  • 120
Jabbir Basha
  • 455
  • 6
  • 7