11

I am using a SharedPreferences in Android.Everything works great in the same session.

However once I relaunch the application, all of the preferences that were set from the previous session are lost.

Is there anything I need to specify to tell the SharedPreferences to hang around from run to run?

I am creating the preferences by calling

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

Then I set properties by e.g.

preferences.edit().putString(key, value);

and I get it by

preferences.getString(key, defaultValue);

Thanks, Victor

Deepan Babu
  • 515
  • 1
  • 6
  • 14
Victor Grazi
  • 15,563
  • 14
  • 61
  • 94
  • 2
    have u written editor.commit() ? – Richa Feb 09 '12 at 04:58
  • 3
    If you're `Set – Sakiboy Sep 08 '16 at 02:04
  • Thank You sooo much Sakiboy. I lost almost 4 hours trying to figure out why after calling commit, and verifying changes while still in the same context, but then switching to another context and the Value I updated reverted back to the old Value. Android please document this stuff and do your job so I can do mine please. 4 hours wasted at the cpu because for some reason Android/Google has poor documentation...geez! – JamisonMan111 Sep 18 '18 at 02:39

8 Answers8

30

SharedPreferences are persistent accross relaunch, restart, I think the problem is you are not commiting the preferences, use following to store values in preferences:

Preferences.Editor edit=preferences.edit();
edit.putString(key, value);
edit.commit();
Victor Grazi
  • 15,563
  • 14
  • 61
  • 94
jeet
  • 29,001
  • 6
  • 52
  • 53
24

You're likely not committing your changes. Set properties like so

SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();

Without the commit you're farting in the wind.

Brian Dupuis
  • 8,136
  • 3
  • 25
  • 29
4

This is working for me please try:

private SharedPreferences mShared;
private Editor mEdit;
mShared = PreferenceManager.getDefaultSharedPreferences(this);

mEdit = mShared.edit();
mEdit.putString(key, value);
mEdit.commit();
deepak Sharma
  • 1,641
  • 10
  • 23
2

to get value in pref

SharedPreferences pref1 = getSharedPreferences(PREFS_NAME, 0);
boolean silent = pref1.getString("silentMode", "...");

to save vlue use onstoe or onPause methds

SharedPreferences pref2 = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = pref2.edit();
editor.putString("silentMode", "...");

That works for me fine and healthy

Nixit Patel
  • 4,435
  • 5
  • 30
  • 57
1

If you are developing for API level ? and above then you should be using editor.apply() instead of editor.commit() when programatically modifying your preferences. editor.commit() has been deprecated, and editor.apply() will handle the actual persistence in the background, which editor.commit() does not do.

Note that editor.apply(), if it fails, does so silently.

Phil Haigh
  • 4,522
  • 1
  • 25
  • 29
  • This is just wrong: commit() is not deprecated at all. The only notice in API 22 is: If you don't care about the return value and you're using this from your application's main thread, consider using {@link #apply} instead. – Stéphane Aug 23 '15 at 17:02
1

This is the code that works for me.

package com.example.persistence;

import android.os.Bundle;
import android.widget.EditText;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


public class MainActivity extends Activity {

public static final String NOTE_PREFS="note";
SharedPreferences msgSettings;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     msgSettings = getSharedPreferences(NOTE_PREFS,0);

      EditText et= (EditText)findViewById(R.id.editText1);
      if (msgSettings.contains(NOTE_PREFS)) {
            et.setText(msgSettings.getString(
                    NOTE_PREFS, "my note")); 

    }

}
@Override
protected void onPause() {
      EditText et= (EditText)findViewById(R.id.editText1);
      String b = et.getText().toString();
      Editor editor = msgSettings.edit();
      editor.putString(NOTE_PREFS,b);
        editor.commit();
    super.onPause();
}
@Override
protected void onDestroy() {
     EditText et= (EditText)findViewById(R.id.editText1);
      String b = et.getText().toString();
      Editor editor = msgSettings.edit();
      editor.putString(NOTE_PREFS,b);
        editor.commit();
    super.onDestroy();
}

    }
0

A lot of time has been past but you may use

.apply() 

instead of

.commit()

that would be better. commit tries to write immediately but apply is asynchronous. here are the explanation from google 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.

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
0

The preferences will not be saved until you commit them, i.e.:

// DON'T DO THIS... See Next Example
preferences.edit().putString(key, value);
preferences.edit().commit();

EDIT: The above has a subtle bug (from comments); you need to keep reference to the editor object, otherwise the above example that commits the value will create a new instance. Should be:

Preferences.Editor edit = preferences.edit();
edit.putString(key, value);
edit.commit();

For reference, from the Android docs:

Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • This code is wrong since you are commiting in a different Editor instance than the one you've put the String. – ffleandro Jul 13 '13 at 19:58
  • @ffleandro - if this code is wrong, then so is every other answer to this question. – Metro Smurf Jul 14 '13 at 00:07
  • 2
    no man, I've seen lots of correct answers. The problem with your answer is that when you call `preferences.edit()` you are creating a `SharedPreferences.Editor` object. When you `commit` you are commiting in a different instance than the one you've called `putString`, hence it will not persist. I recommend you read again the `docs` you posted. – ffleandro Jul 14 '13 at 13:53