1

I have two activities. In the first activity, I'm putting a String into a shared preference. I then log the getString and I see that it shows up. I then move onto the second activity, and I Toast the getString and I get the default value that shows up.

The first activity code:

SharedPreferences.Editor pref_editor = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE).edit();
SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
pref_editor.putString("test", "It works!").commit();
Log.d("XXX", pref.getString("test", "ERRRROR"));

The second activity code:

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String current = pref.getString("test", "ERROR");
Toast.makeText(getApplicationContext(), current,
                Toast.LENGTH_SHORT).show();

Any idea why I'm getting the default value of "ERROR" when I toast?

EGHDK
  • 17,818
  • 45
  • 129
  • 204

3 Answers3

2

Please try this:-

SharedPreferences pref = mcontext.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor pref_editor = pref.edit();
pref_editor.putString("test", "It works!")
pref_editor.commit();
Swati Rawat
  • 1,729
  • 1
  • 19
  • 34
0

You aren't calling commit on the editor. The changes are batched and not written to disk until commit is called.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

From this SO post Have you tried apply()?

Community
  • 1
  • 1
Chuck D
  • 1,629
  • 2
  • 16
  • 32