EGHDK
EGHDK

Reputation: 18130

Accessing SharedPreference not working in Android

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?

Upvotes: 1

Views: 117

Answers (3)

Swati Rawat
Swati Rawat

Reputation: 1729

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();

Upvotes: 2

Chuck D
Chuck D

Reputation: 1809

From this SO post Have you tried apply()?

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

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

Upvotes: 0

Related Questions